The following issues were found

Lib/idlelib/idle_test/test_squeezer.py
14 issues
Assigning result of a function call, where the function has no return
Error

Line: 422 Column: 9

                      expandingbutton.clipboard_append = Mock()

        # Trigger the copy event.
        retval = expandingbutton.copy(event=Mock())
        self.assertEqual(retval, None)

        # Vheck that the expanding button called clipboard_clear() and
        # clipboard_append('TEXT') once each.
        self.assertEqual(expandingbutton.clipboard_clear.call_count, 1)

            

Reported by Pylint.

Use of possibly insecure function - consider using safer ast.literal_eval.
Security blacklist

Line: 134
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval

                          with self.subTest(text_code=text_code,
                              line_width=line_width,
                              expected=expected):
                text = eval(text_code)
                with patch.object(editwin, 'width', line_width):
                    self.assertEqual(squeezer.count_lines(text), expected)

    def test_init(self):
        """Test the creation of Squeezer instances."""

            

Reported by Bandit.

Use of eval
Error

Line: 134 Column: 24

                          with self.subTest(text_code=text_code,
                              line_width=line_width,
                              expected=expected):
                text = eval(text_code)
                with patch.object(editwin, 'width', line_width):
                    self.assertEqual(squeezer.count_lines(text), expected)

    def test_init(self):
        """Test the creation of Squeezer instances."""

            

Reported by Pylint.

Unused variable 'data'
Error

Line: 461 Column: 25

                          expandingbutton.context_menu_event(event=mock_event)
            self.assertEqual(mock_menu.add_command.call_count,
                             len(expandingbutton.rmenu_specs))
            for label, *data in expandingbutton.rmenu_specs:
                mock_menu.add_command.assert_any_call(label=label, command=ANY)


if __name__ == '__main__':
    unittest.main(verbosity=2)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 36 Column: 5

              
class CountLinesTest(unittest.TestCase):
    """Tests for the count_lines_with_wrapping function."""
    def check(self, expected, text, linewidth):
        return self.assertEqual(
            expected,
            count_lines_with_wrapping(text, linewidth),
        )


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 58 Column: 5

                      """Test with several lines of text."""
        self.assertEqual(count_lines_with_wrapping("1\n2\n3\n"), 3)

    def test_empty_lines(self):
        self.check(expected=1, text='\n', linewidth=80)
        self.check(expected=2, text='\n\n', linewidth=80)
        self.check(expected=10, text='\n' * 10, linewidth=80)

    def test_long_line(self):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 63 Column: 5

                      self.check(expected=2, text='\n\n', linewidth=80)
        self.check(expected=10, text='\n' * 10, linewidth=80)

    def test_long_line(self):
        self.check(expected=3, text='a' * 200, linewidth=80)
        self.check(expected=3, text='a' * 200 + '\n', linewidth=80)

    def test_several_lines_different_lengths(self):
        text = dedent("""\

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 67 Column: 5

                      self.check(expected=3, text='a' * 200, linewidth=80)
        self.check(expected=3, text='a' * 200 + '\n', linewidth=80)

    def test_several_lines_different_lengths(self):
        text = dedent("""\
            13 characters
            43 is the number of characters on this line

            7 chars

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 102 Column: 5

                      squeezer = Squeezer(editor_window)
        return squeezer

    def make_text_widget(self, root=None):
        if root is None:
            root = get_test_tk_root(self)
        text_widget = Text(root)
        text_widget["font"] = ('Courier', 10)
        text_widget.mark_set("iomark", "1.0")

            

Reported by Pylint.

Argument name "configType" doesn't conform to snake_case naming style
Error

Line: 110 Column: 5

                      text_widget.mark_set("iomark", "1.0")
        return text_widget

    def set_idleconf_option_with_cleanup(self, configType, section, option, value):
        prev_val = idleConf.GetOption(configType, section, option)
        idleConf.SetOption(configType, section, option, value)
        self.addCleanup(idleConf.SetOption,
                        configType, section, option, prev_val)


            

Reported by Pylint.

Lib/ensurepip/__init__.py
14 issues
Using variable '_PACKAGES' before assignment
Error

Line: 63 Column: 8

              
def _get_packages():
    global _PACKAGES, _WHEEL_PKG_DIR
    if _PACKAGES is not None:
        return _PACKAGES

    packages = {}
    for name, version, py_tag in _PROJECTS:
        wheel_name = f"{name}-{version}-{py_tag}-none-any.whl"

            

Reported by Pylint.

Redefining name 'version' from outer scope (line 96)
Error

Line: 55 Column: 9

                          continue

        # Extract '20.2.2' from 'pip-20.2.2-py2.py3-none-any.whl'
        version = filename.removeprefix(prefix).partition('-')[0]
        wheel_path = os.path.join(path, filename)
        packages[name] = _Package(version, None, wheel_path)
    return packages



            

Reported by Pylint.

Using the global statement
Error

Line: 62 Column: 5

              

def _get_packages():
    global _PACKAGES, _WHEEL_PKG_DIR
    if _PACKAGES is not None:
        return _PACKAGES

    packages = {}
    for name, version, py_tag in _PROJECTS:

            

Reported by Pylint.

Redefining name 'version' from outer scope (line 96)
Error

Line: 67 Column: 15

                      return _PACKAGES

    packages = {}
    for name, version, py_tag in _PROJECTS:
        wheel_name = f"{name}-{version}-{py_tag}-none-any.whl"
        packages[name] = _Package(version, wheel_name, None)
    if _WHEEL_PKG_DIR:
        dir_packages = _find_packages(_WHEEL_PKG_DIR)
        # only used the wheel package directory if all packages are found there

            

Reported by Pylint.

Unused variable 'name'
Error

Line: 163 Column: 13

                      # Put our bundled wheels into a temporary directory and construct the
        # additional paths that need added to sys.path
        additional_paths = []
        for name, package in _get_packages().items():
            if package.wheel_name:
                # Use bundled wheel package
                wheel_name = package.wheel_name
                wheel_path = resources.files("ensurepip") / "_bundled" / wheel_name
                whl = wheel_path.read_bytes()

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import collections
import os
import os.path
import subprocess
import sys
import sysconfig
import tempfile
from importlib import resources


            

Reported by Pylint.

Consider possible security implications associated with subprocess module.
Security blacklist

Line: 4
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b404-import-subprocess

              import collections
import os
import os.path
import subprocess
import sys
import sysconfig
import tempfile
from importlib import resources


            

Reported by Bandit.

subprocess call - check for execution of untrusted input.
Security injection

Line: 92
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b603_subprocess_without_shell_equals_true.html

              sys.argv[1:] = {args}
runpy.run_module("pip", run_name="__main__", alter_sys=True)
"""
    return subprocess.run([sys.executable, '-W', 'ignore::DeprecationWarning',
                           "-c", code], check=True).returncode


def version():
    """

            

Reported by Bandit.

Too many local variables (16/15)
Error

Line: 130 Column: 1

                             verbosity=verbosity)


def _bootstrap(*, root=None, upgrade=False, user=False,
              altinstall=False, default_pip=False,
              verbosity=0):
    """
    Bootstrap pip into the current Python installation (or the given root
    directory). Returns pip command status code.

            

Reported by Pylint.

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

Line: 171 Column: 56

                              whl = wheel_path.read_bytes()
            else:
                # Use the wheel package directory
                with open(package.wheel_path, "rb") as fp:
                    whl = fp.read()
                wheel_name = os.path.basename(package.wheel_path)

            filename = os.path.join(tmpdir, wheel_name)
            with open(filename, "wb") as fp:

            

Reported by Pylint.

Modules/clinic/_tkinter.c.h
14 issues
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: 31 Column: 9 CWE codes: 126

                  if (script == NULL) {
        goto exit;
    }
    if (strlen(script) != (size_t)script_length) {
        PyErr_SetString(PyExc_ValueError, "embedded null character");
        goto exit;
    }
    return_value = _tkinter_tkapp_eval_impl(self, script);


            

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: 67 Column: 9 CWE codes: 126

                  if (fileName == NULL) {
        goto exit;
    }
    if (strlen(fileName) != (size_t)fileName_length) {
        PyErr_SetString(PyExc_ValueError, "embedded null character");
        goto exit;
    }
    return_value = _tkinter_tkapp_evalfile_impl(self, fileName);


            

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: 103 Column: 9 CWE codes: 126

                  if (script == NULL) {
        goto exit;
    }
    if (strlen(script) != (size_t)script_length) {
        PyErr_SetString(PyExc_ValueError, "embedded null character");
        goto exit;
    }
    return_value = _tkinter_tkapp_record_impl(self, script);


            

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: 139 Column: 9 CWE codes: 126

                  if (msg == NULL) {
        goto exit;
    }
    if (strlen(msg) != (size_t)msg_length) {
        PyErr_SetString(PyExc_ValueError, "embedded null character");
        goto exit;
    }
    return_value = _tkinter_tkapp_adderrorinfo_impl(self, msg);


            

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: 199 Column: 9 CWE codes: 126

                  if (s == NULL) {
        goto exit;
    }
    if (strlen(s) != (size_t)s_length) {
        PyErr_SetString(PyExc_ValueError, "embedded null character");
        goto exit;
    }
    return_value = _tkinter_tkapp_exprstring_impl(self, s);


            

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: 235 Column: 9 CWE codes: 126

                  if (s == NULL) {
        goto exit;
    }
    if (strlen(s) != (size_t)s_length) {
        PyErr_SetString(PyExc_ValueError, "embedded null character");
        goto exit;
    }
    return_value = _tkinter_tkapp_exprlong_impl(self, s);


            

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: 271 Column: 9 CWE codes: 126

                  if (s == NULL) {
        goto exit;
    }
    if (strlen(s) != (size_t)s_length) {
        PyErr_SetString(PyExc_ValueError, "embedded null character");
        goto exit;
    }
    return_value = _tkinter_tkapp_exprdouble_impl(self, s);


            

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: 307 Column: 9 CWE codes: 126

                  if (s == NULL) {
        goto exit;
    }
    if (strlen(s) != (size_t)s_length) {
        PyErr_SetString(PyExc_ValueError, "embedded null character");
        goto exit;
    }
    return_value = _tkinter_tkapp_exprboolean_impl(self, s);


            

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: 364 Column: 9 CWE codes: 126

                  if (name == NULL) {
        goto exit;
    }
    if (strlen(name) != (size_t)name_length) {
        PyErr_SetString(PyExc_ValueError, "embedded null character");
        goto exit;
    }
    func = args[1];
    return_value = _tkinter_tkapp_createcommand_impl(self, name, func);

            

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: 401 Column: 9 CWE codes: 126

                  if (name == NULL) {
        goto exit;
    }
    if (strlen(name) != (size_t)name_length) {
        PyErr_SetString(PyExc_ValueError, "embedded null character");
        goto exit;
    }
    return_value = _tkinter_tkapp_deletecommand_impl(self, name);


            

Reported by FlawFinder.

Lib/xml/parsers/expat.py
14 issues
Unused import version_info from wildcard import
Error

Line: 4 Column: 1

              """Interface to the Expat non-validating XML parser."""
import sys

from pyexpat import *

# provide pyexpat submodules as xml.parsers.expat submodules
sys.modules['xml.parsers.expat.model'] = model
sys.modules['xml.parsers.expat.errors'] = errors

            

Reported by Pylint.

Wildcard import pyexpat
Error

Line: 4 Column: 1

              """Interface to the Expat non-validating XML parser."""
import sys

from pyexpat import *

# provide pyexpat submodules as xml.parsers.expat submodules
sys.modules['xml.parsers.expat.model'] = model
sys.modules['xml.parsers.expat.errors'] = errors

            

Reported by Pylint.

Unused import EXPAT_VERSION from wildcard import
Error

Line: 4 Column: 1

              """Interface to the Expat non-validating XML parser."""
import sys

from pyexpat import *

# provide pyexpat submodules as xml.parsers.expat submodules
sys.modules['xml.parsers.expat.model'] = model
sys.modules['xml.parsers.expat.errors'] = errors

            

Reported by Pylint.

Unused import native_encoding from wildcard import
Error

Line: 4 Column: 1

              """Interface to the Expat non-validating XML parser."""
import sys

from pyexpat import *

# provide pyexpat submodules as xml.parsers.expat submodules
sys.modules['xml.parsers.expat.model'] = model
sys.modules['xml.parsers.expat.errors'] = errors

            

Reported by Pylint.

Unused import features from wildcard import
Error

Line: 4 Column: 1

              """Interface to the Expat non-validating XML parser."""
import sys

from pyexpat import *

# provide pyexpat submodules as xml.parsers.expat submodules
sys.modules['xml.parsers.expat.model'] = model
sys.modules['xml.parsers.expat.errors'] = errors

            

Reported by Pylint.

Unused import expat_CAPI from wildcard import
Error

Line: 4 Column: 1

              """Interface to the Expat non-validating XML parser."""
import sys

from pyexpat import *

# provide pyexpat submodules as xml.parsers.expat submodules
sys.modules['xml.parsers.expat.model'] = model
sys.modules['xml.parsers.expat.errors'] = errors

            

Reported by Pylint.

Unused import error from wildcard import
Error

Line: 4 Column: 1

              """Interface to the Expat non-validating XML parser."""
import sys

from pyexpat import *

# provide pyexpat submodules as xml.parsers.expat submodules
sys.modules['xml.parsers.expat.model'] = model
sys.modules['xml.parsers.expat.errors'] = errors

            

Reported by Pylint.

Unused import XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE from wildcard import
Error

Line: 4 Column: 1

              """Interface to the Expat non-validating XML parser."""
import sys

from pyexpat import *

# provide pyexpat submodules as xml.parsers.expat submodules
sys.modules['xml.parsers.expat.model'] = model
sys.modules['xml.parsers.expat.errors'] = errors

            

Reported by Pylint.

Unused import XML_PARAM_ENTITY_PARSING_NEVER from wildcard import
Error

Line: 4 Column: 1

              """Interface to the Expat non-validating XML parser."""
import sys

from pyexpat import *

# provide pyexpat submodules as xml.parsers.expat submodules
sys.modules['xml.parsers.expat.model'] = model
sys.modules['xml.parsers.expat.errors'] = errors

            

Reported by Pylint.

Unused import XML_PARAM_ENTITY_PARSING_ALWAYS from wildcard import
Error

Line: 4 Column: 1

              """Interface to the Expat non-validating XML parser."""
import sys

from pyexpat import *

# provide pyexpat submodules as xml.parsers.expat submodules
sys.modules['xml.parsers.expat.model'] = model
sys.modules['xml.parsers.expat.errors'] = errors

            

Reported by Pylint.

Lib/test/test_utf8source.py
14 issues
Cannot import 'test.badsyntax_pep3120' due to syntax error "invalid or missing encoding declaration for '/home/javierd/TFG/inputs/65/Lib/test/badsyntax_pep3120.py'"
Error

Line: 19 Column: 1

              
    def test_badsyntax(self):
        try:
            import test.badsyntax_pep3120
        except SyntaxError as msg:
            msg = str(msg).lower()
            self.assertTrue('utf-8' in msg)
        else:
            self.fail("expected exception didn't occur")

            

Reported by Pylint.

No name 'badsyntax_pep3120' in module 'test'
Error

Line: 19 Column: 13

              
    def test_badsyntax(self):
        try:
            import test.badsyntax_pep3120
        except SyntaxError as msg:
            msg = str(msg).lower()
            self.assertTrue('utf-8' in msg)
        else:
            self.fail("expected exception didn't occur")

            

Reported by Pylint.

Anomalous backslash in string: '\П'. String constant might be missing an r prefix.
Error

Line: 13 Column: 14

                          b'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
        )
        self.assertEqual(
            "\П".encode("utf-8"),
            b'\\\xd0\x9f'
        )

    def test_badsyntax(self):
        try:

            

Reported by Pylint.

Unused import test.badsyntax_pep3120
Error

Line: 19 Column: 13

              
    def test_badsyntax(self):
        try:
            import test.badsyntax_pep3120
        except SyntaxError as msg:
            msg = str(msg).lower()
            self.assertTrue('utf-8' in msg)
        else:
            self.fail("expected exception didn't occur")

            

Reported by Pylint.

Use of exec detected.
Security

Line: 38
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html

                      except SyntaxError:
            self.fail("compile() cannot handle Latin-1 source")
        ns = {}
        exec(code, ns)
        self.assertEqual('Ç', ns['u'])


if __name__ == "__main__":
    unittest.main()

            

Reported by Bandit.

Use of exec
Error

Line: 38 Column: 9

                      except SyntaxError:
            self.fail("compile() cannot handle Latin-1 source")
        ns = {}
        exec(code, ns)
        self.assertEqual('Ç', ns['u'])


if __name__ == "__main__":
    unittest.main()

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # This file is marked as binary in the CVS, to prevent MacCVS from recoding it.

import unittest

class PEP3120Test(unittest.TestCase):

    def test_pep3120(self):
        self.assertEqual(
            "Питон".encode("utf-8"),

            

Reported by Pylint.

Missing class docstring
Error

Line: 5 Column: 1

              
import unittest

class PEP3120Test(unittest.TestCase):

    def test_pep3120(self):
        self.assertEqual(
            "Питон".encode("utf-8"),
            b'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 7 Column: 5

              
class PEP3120Test(unittest.TestCase):

    def test_pep3120(self):
        self.assertEqual(
            "Питон".encode("utf-8"),
            b'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
        )
        self.assertEqual(

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 17 Column: 5

                          b'\\\xd0\x9f'
        )

    def test_badsyntax(self):
        try:
            import test.badsyntax_pep3120
        except SyntaxError as msg:
            msg = str(msg).lower()
            self.assertTrue('utf-8' in msg)

            

Reported by Pylint.

PC/layout/support/pip.py
14 issues
Attempted relative import beyond top-level package
Error

Line: 14 Column: 1

              import subprocess
import sys

from .filesets import *

__all__ = ["extract_pip_files", "get_pip_layout"]


def get_pip_dir(ns):

            

Reported by Pylint.

Undefined variable 'log_warning'
Error

Line: 31 Column: 9

              def get_pip_layout(ns):
    pip_dir = get_pip_dir(ns)
    if not pip_dir.is_dir():
        log_warning("Failed to find {} - pip will not be included", pip_dir)
    else:
        pkg_root = "packages/{}" if ns.zip_lib else "Lib/site-packages/{}"
        for dest, src in rglob(pip_dir, "**/*"):
            yield pkg_root.format(dest), src
        if ns.include_pip_user:

            

Reported by Pylint.

Undefined variable 'rglob'
Error

Line: 34 Column: 26

                      log_warning("Failed to find {} - pip will not be included", pip_dir)
    else:
        pkg_root = "packages/{}" if ns.zip_lib else "Lib/site-packages/{}"
        for dest, src in rglob(pip_dir, "**/*"):
            yield pkg_root.format(dest), src
        if ns.include_pip_user:
            content = "\n".join(
                "[{}]\nuser=yes".format(n)
                for n in ["install", "uninstall", "freeze", "list"]

            

Reported by Pylint.

Wildcard import filesets
Error

Line: 14 Column: 1

              import subprocess
import sys

from .filesets import *

__all__ = ["extract_pip_files", "get_pip_layout"]


def get_pip_dir(ns):

            

Reported by Pylint.

Unused variable 'output'
Error

Line: 62 Column: 5

                  env = os.environ.copy()
    env["PYTHONPATH"] = search_path

    output = subprocess.check_output(
        [
            sys.executable,
            "-m",
            "pip",
            "--no-color",

            

Reported by Pylint.

Consider possible security implications associated with subprocess module.
Security blacklist

Line: 11
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b404-import-subprocess

              
import os
import shutil
import subprocess
import sys

from .filesets import *

__all__ = ["extract_pip_files", "get_pip_layout"]

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 19 Column: 1

              __all__ = ["extract_pip_files", "get_pip_layout"]


def get_pip_dir(ns):
    if ns.copy:
        if ns.zip_lib:
            return ns.copy / "packages"
        return ns.copy / "Lib" / "site-packages"
    else:

            

Reported by Pylint.

Argument name "ns" doesn't conform to snake_case naming style
Error

Line: 19 Column: 1

              __all__ = ["extract_pip_files", "get_pip_layout"]


def get_pip_dir(ns):
    if ns.copy:
        if ns.zip_lib:
            return ns.copy / "packages"
        return ns.copy / "Lib" / "site-packages"
    else:

            

Reported by Pylint.

Unnecessary "else" after "return"
Error

Line: 20 Column: 5

              

def get_pip_dir(ns):
    if ns.copy:
        if ns.zip_lib:
            return ns.copy / "packages"
        return ns.copy / "Lib" / "site-packages"
    else:
        return ns.temp / "packages"

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 28 Column: 1

                      return ns.temp / "packages"


def get_pip_layout(ns):
    pip_dir = get_pip_dir(ns)
    if not pip_dir.is_dir():
        log_warning("Failed to find {} - pip will not be included", pip_dir)
    else:
        pkg_root = "packages/{}" if ns.zip_lib else "Lib/site-packages/{}"

            

Reported by Pylint.

Modules/_datetimemodule.c
14 issues
char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

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

              static PyObject *
make_freplacement(PyObject *object)
{
    char freplacement[64];
    if (PyTime_Check(object))
        sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
    else if (PyDateTime_Check(object))
        sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
    else

            

Reported by FlawFinder.

sprintf - Does not check for buffer overflows
Security

Line: 1461 Column: 9 CWE codes: 120
Suggestion: Use sprintf_s, snprintf, or vsnprintf

              {
    char freplacement[64];
    if (PyTime_Check(object))
        sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
    else if (PyDateTime_Check(object))
        sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
    else
        sprintf(freplacement, "%06d", 0);


            

Reported by FlawFinder.

sprintf - Does not check for buffer overflows
Security

Line: 1463 Column: 9 CWE codes: 120
Suggestion: Use sprintf_s, snprintf, or vsnprintf

                  if (PyTime_Check(object))
        sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
    else if (PyDateTime_Check(object))
        sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
    else
        sprintf(freplacement, "%06d", 0);

    return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
}

            

Reported by FlawFinder.

sprintf - Does not check for buffer overflows
Security

Line: 1465 Column: 9 CWE codes: 120
Suggestion: Use sprintf_s, snprintf, or vsnprintf

                  else if (PyDateTime_Check(object))
        sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
    else
        sprintf(freplacement, "%06d", 0);

    return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
}

/* I sure don't want to reproduce the strftime code from the time module,

            

Reported by FlawFinder.

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

Line: 1540 Column: 17 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

                      else if (ch == 'z') {
            if (zreplacement == NULL) {
                /* format utcoffset */
                char buf[100];
                PyObject *tzinfo = get_tzinfo_member(object);
                zreplacement = PyBytes_FromStringAndSize("", 0);
                if (zreplacement == NULL) goto Done;
                if (tzinfo != Py_None && tzinfo != NULL) {
                    assert(tzinfoarg != NULL);

            

Reported by FlawFinder.

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

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

                              goto Done;
            pnew = PyBytes_AsString(newfmt) + usednew;
        }
        memcpy(pnew, ptoappend, ntoappend);
        pnew += ntoappend;
        usednew += ntoappend;
        assert(usednew <= totalnew);
    }  /* end while() */


            

Reported by FlawFinder.

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

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

                  me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
    if (me != NULL) {
        const char *pdata = PyBytes_AS_STRING(state);
        memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
        me->hashcode = -1;
    }
    return (PyObject *)me;
}


            

Reported by FlawFinder.

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

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

                  if (me != NULL) {
        const char *pdata = PyBytes_AS_STRING(state);

        memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
        me->hashcode = -1;
        me->hastzinfo = aware;
        if (aware) {
            Py_INCREF(tzinfo);
            me->tzinfo = tzinfo;

            

Reported by FlawFinder.

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

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

              static PyObject *
time_isoformat(PyDateTime_Time *self, PyObject *args, PyObject *kw)
{
    char buf[100];
    const char *timespec = NULL;
    static char *keywords[] = {"timespec", NULL};
    PyObject *result;
    int us = TIME_GET_MICROSECOND(self);
    static const char *specs[][2] = {

            

Reported by FlawFinder.

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

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

                  if (me != NULL) {
        const char *pdata = PyBytes_AS_STRING(state);

        memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
        me->hashcode = -1;
        me->hastzinfo = aware;
        if (aware) {
            Py_INCREF(tzinfo);
            me->tzinfo = tzinfo;

            

Reported by FlawFinder.

Python/marshal.c
14 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

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

                  m = p->end - p->ptr;
    if (p->fp != NULL) {
        if (n <= m) {
            memcpy(p->ptr, s, n);
            p->ptr += n;
        }
        else {
            w_flush(p);
            fwrite(s, 1, n, p->fp);

            

Reported by FlawFinder.

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

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

                  }
    else {
        if (n <= m || w_reserve(p, n - m)) {
            memcpy(p->ptr, s, n);
            p->ptr += n;
        }
    }
}


            

Reported by FlawFinder.

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

Line: 273 Column: 14 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

              static void
w_float_bin(double v, WFILE *p)
{
    unsigned char buf[8];
    if (_PyFloat_Pack8(v, buf, 1) < 0) {
        p->error = WFERR_UNMARSHALLABLE;
        return;
    }
    w_string(buf, 8, p);

            

Reported by FlawFinder.

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

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

              void
PyMarshal_WriteLongToFile(long x, FILE *fp, int version)
{
    char buf[4];
    WFILE wf;
    memset(&wf, 0, sizeof(wf));
    wf.fp = fp;
    wf.ptr = wf.buf = buf;
    wf.end = wf.ptr + sizeof(buf);

            

Reported by FlawFinder.

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

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

              void
PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version)
{
    char buf[BUFSIZ];
    WFILE wf;
    if (PySys_Audit("marshal.dumps", "Oi", x, version) < 0) {
        return; /* caller must check PyErr_Occurred() */
    }
    memset(&wf, 0, sizeof(wf));

            

Reported by FlawFinder.

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

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

              r_float_str(RFILE *p)
{
    int n;
    char buf[256];
    const char *ptr;
    n = r_byte(p);
    if (n == EOF) {
        PyErr_SetString(PyExc_EOFError,
            "EOF read where object expected");

            

Reported by FlawFinder.

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

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

                  if (ptr == NULL) {
        return -1;
    }
    memcpy(buf, ptr, n);
    buf[n] = '\0';
    return PyOS_string_to_double(buf, NULL, NULL);
}

/* allocate the reflist index for a new object. Return -1 on failure */

            

Reported by FlawFinder.

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

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

                              Py_DECREF(v);
                break;
            }
            memcpy(PyBytes_AS_STRING(v), ptr, n);
            retval = v;
            R_REF(retval);
            break;
        }


            

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: 289 Column: 26 CWE codes: 126

                      p->error = WFERR_NOMEMORY;
        return;
    }
    w_short_pstring(buf, strlen(buf), p);
    PyMem_Free(buf);
}

static int
w_ref(PyObject *v, char *flag, WFILE *p)

            

Reported by FlawFinder.

read - Check buffer boundaries if used in a loop including recursive loops
Security

Line: 686 Column: 9 CWE codes: 120 20

                          Py_DECREF(res);
        }
    }
    if (read != n) {
        if (!PyErr_Occurred()) {
            if (read > n)
                PyErr_Format(PyExc_ValueError,
                             "read() returned too much data: "
                             "%zd bytes requested, %zd returned",

            

Reported by FlawFinder.

Lib/uu.py
14 issues
Uses of a deprecated module 'optparse'
Error

Line: 170 Column: 5

              def test():
    """uuencode/uudecode main program"""

    import optparse
    parser = optparse.OptionParser(usage='usage: %prog [-d] [-t] [input [output]]')
    parser.add_option('-d', '--decode', dest='decode', help='Decode (instead of encode)?', default=False, action='store_true')
    parser.add_option('-t', '--text', dest='text', help='data is text, encoded format unix-compatible text?', default=False, action='store_true')

    (options, args) = parser.parse_args()

            

Reported by Pylint.

Redefining built-in 'input'
Error

Line: 181 Column: 5

                      sys.exit(1)

    # Use the binary streams underlying stdin/stdout
    input = sys.stdin.buffer
    output = sys.stdout.buffer
    if len(args) > 0:
        input = args[0]
    if len(args) > 1:
        output = args[1]

            

Reported by Pylint.

Missing class docstring
Error

Line: 39 Column: 1

              
__all__ = ["Error", "encode", "decode"]

class Error(Exception):
    pass

def encode(in_file, out_file, name=None, mode=None, *, backtick=False):
    """Uuencode file"""
    #

            

Reported by Pylint.

Too many branches (15/12)
Error

Line: 42 Column: 1

              class Error(Exception):
    pass

def encode(in_file, out_file, name=None, mode=None, *, backtick=False):
    """Uuencode file"""
    #
    # If in_file is a pathname open it and change defaults
    #
    opened_files = []

            

Reported by Pylint.

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

Line: 96 Column: 13

                      else:
            out_file.write(b' \nend\n')
    finally:
        for f in opened_files:
            f.close()


def decode(in_file, out_file=None, mode=None, quiet=False):
    """Decode uuencoded file"""

            

Reported by Pylint.

Too many branches (19/12)
Error

Line: 100 Column: 1

                          f.close()


def decode(in_file, out_file=None, mode=None, quiet=False):
    """Decode uuencoded file"""
    #
    # Open the input file, if needed.
    #
    opened_files = []

            

Reported by Pylint.

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

Line: 142 Column: 13

                      if out_file == '-':
            out_file = sys.stdout.buffer
        elif isinstance(out_file, str):
            fp = open(out_file, 'wb')
            os.chmod(out_file, mode)
            out_file = fp
            opened_files.append(out_file)
        #
        # Main decoding loop

            

Reported by Pylint.

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

Line: 149 Column: 9

                      #
        # Main decoding loop
        #
        s = in_file.readline()
        while s and s.strip(b' \t\r\n\f') != b'end':
            try:
                data = binascii.a2b_uu(s)
            except binascii.Error as v:
                # Workaround for broken uuencoders by /Fredrik Lundh

            

Reported by Pylint.

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

Line: 153 Column: 13

                      while s and s.strip(b' \t\r\n\f') != b'end':
            try:
                data = binascii.a2b_uu(s)
            except binascii.Error as v:
                # Workaround for broken uuencoders by /Fredrik Lundh
                nbytes = (((s[0]-32) & 63) * 4 + 5) // 3
                data = binascii.a2b_uu(s[:nbytes])
                if not quiet:
                    sys.stderr.write("Warning: %s\n" % v)

            

Reported by Pylint.

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

Line: 160 Column: 13

                              if not quiet:
                    sys.stderr.write("Warning: %s\n" % v)
            out_file.write(data)
            s = in_file.readline()
        if not s:
            raise Error('Truncated input file')
    finally:
        for f in opened_files:
            f.close()

            

Reported by Pylint.

Modules/_testbuffer.c
14 issues
strcpy - Does not check for buffer overflows when copying to destination [MS-banned]
Security

Line: 815 Column: 5 CWE codes: 120
Suggestion: Consider using snprintf, strcpy_s, or strlcpy (warning: strncpy easily misused)

                      Py_DECREF(tmp);
        return NULL;
    }
    strcpy(fmt, PyBytes_AS_STRING(tmp));
    Py_DECREF(tmp);

    return fmt;
}


            

Reported by FlawFinder.

strcpy - Does not check for buffer overflows when copying to destination [MS-banned]
Security

Line: 2278 Column: 9 CWE codes: 120
Suggestion: Consider using snprintf, strcpy_s, or strlcpy (warning: strncpy easily misused)

                              ND_MAX_NDIM);
                return NULL;
        }
        strcpy(format, view->format);
        info.format = format;
    }
    if (view->ndim > ND_MAX_NDIM) {
        PyErr_Format(PyExc_TypeError,
            "memoryview_from_buffer: ndim is limited to %d", ND_MAX_NDIM);

            

Reported by FlawFinder.

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

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

                          assert(mem != NULL);
            for (i=0, p=mem; i<shape[0]; p+=itemsize, sptr+=sstrides[0], i++) {
                char *xsptr = ADJUST_PTR(sptr, ssuboffsets);
                memcpy(p, xsptr, itemsize);
            }
            for (i=0, p=mem; i<shape[0]; p+=itemsize, dptr+=dstrides[0], i++) {
                char *xdptr = ADJUST_PTR(dptr, dsuboffsets);
                memcpy(xdptr, p, itemsize);
            }

            

Reported by FlawFinder.

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

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

                          }
            for (i=0, p=mem; i<shape[0]; p+=itemsize, dptr+=dstrides[0], i++) {
                char *xdptr = ADJUST_PTR(dptr, dsuboffsets);
                memcpy(xdptr, p, itemsize);
            }
        }
        return;
    }


            

Reported by FlawFinder.

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

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

                  assert(strides != NULL);

    if (ndim == 0) {
        memcpy(item, ptr, itemsize);
        x = PyObject_CallFunctionObjArgs(unpack_from, mview, NULL);
        if (x == NULL)
            return NULL;
        if (PyTuple_GET_SIZE(x) == 1) {
            PyObject *tmp = PyTuple_GET_ITEM(x, 0);

            

Reported by FlawFinder.

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

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

                      return -1;
    }

    memcpy(data + addsize, ndbuf->data, ndbuf->len);

    PyMem_Free(ndbuf->data);
    ndbuf->data = data;
    ndbuf->len += addsize;
    base->buf = ndbuf->data;

            

Reported by FlawFinder.

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

Line: 2237 Column: 12 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

                  const NDArrayObject *nd = (NDArrayObject *)self;
    const Py_buffer *view = &nd->head->base;
    const ndbuf_t *ndbuf;
    static char format[ND_MAX_NDIM+1];
    static Py_ssize_t shape[ND_MAX_NDIM];
    static Py_ssize_t strides[ND_MAX_NDIM];
    static Py_ssize_t suboffsets[ND_MAX_NDIM];
    static Py_buffer info;
    char *p;

            

Reported by FlawFinder.

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

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

                      infobuf = p;
    }
    /* copy the complete raw data */
    memcpy(infobuf, ndbuf->data, ndbuf->len);
    info.buf = infobuf + ((char *)view->buf - ndbuf->data);

    if (view->format) {
        if (strlen(view->format) > ND_MAX_NDIM) {
            PyErr_Format(PyExc_TypeError,

            

Reported by FlawFinder.

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

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

                          return NULL;
    }
    if (view->shape) {
        memcpy(shape, view->shape, view->ndim * sizeof(Py_ssize_t));
        info.shape = shape;
    }
    if (view->strides) {
        memcpy(strides, view->strides, view->ndim * sizeof(Py_ssize_t));
        info.strides = strides;

            

Reported by FlawFinder.

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

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

                      info.shape = shape;
    }
    if (view->strides) {
        memcpy(strides, view->strides, view->ndim * sizeof(Py_ssize_t));
        info.strides = strides;
    }
    if (view->suboffsets) {
        memcpy(suboffsets, view->suboffsets, view->ndim * sizeof(Py_ssize_t));
        info.suboffsets = suboffsets;

            

Reported by FlawFinder.