The following issues were found

Lib/test/test_xdrlib.py
15 issues
Missing module docstring
Error

Line: 1 Column: 1

              import unittest

import xdrlib

class XDRTest(unittest.TestCase):

    def test_xdr(self):
        p = xdrlib.Packer()


            

Reported by Pylint.

Missing class docstring
Error

Line: 5 Column: 1

              
import xdrlib

class XDRTest(unittest.TestCase):

    def test_xdr(self):
        p = xdrlib.Packer()

        s = b'hello world'

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 7 Column: 5

              
class XDRTest(unittest.TestCase):

    def test_xdr(self):
        p = xdrlib.Packer()

        s = b'hello world'
        a = [b'what', b'is', b'hapnin', b'doctor']


            

Reported by Pylint.

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

Line: 8 Column: 9

              class XDRTest(unittest.TestCase):

    def test_xdr(self):
        p = xdrlib.Packer()

        s = b'hello world'
        a = [b'what', b'is', b'hapnin', b'doctor']

        p.pack_int(42)

            

Reported by Pylint.

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

Line: 10 Column: 9

                  def test_xdr(self):
        p = xdrlib.Packer()

        s = b'hello world'
        a = [b'what', b'is', b'hapnin', b'doctor']

        p.pack_int(42)
        p.pack_int(-17)
        p.pack_uint(9)

            

Reported by Pylint.

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

Line: 11 Column: 9

                      p = xdrlib.Packer()

        s = b'hello world'
        a = [b'what', b'is', b'hapnin', b'doctor']

        p.pack_int(42)
        p.pack_int(-17)
        p.pack_uint(9)
        p.pack_bool(True)

            

Reported by Pylint.

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

Line: 27 Column: 9

              
        # now verify
        data = p.get_buffer()
        up = xdrlib.Unpacker(data)

        self.assertEqual(up.get_position(), 0)

        self.assertEqual(up.unpack_int(), 42)
        self.assertEqual(up.unpack_int(), -17)

            

Reported by Pylint.

Missing class docstring
Error

Line: 53 Column: 1

                      up.done()
        self.assertRaises(EOFError, up.unpack_uint)

class ConversionErrorTest(unittest.TestCase):

    def setUp(self):
        self.packer = xdrlib.Packer()

    def assertRaisesConversion(self, *args):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 58 Column: 5

                  def setUp(self):
        self.packer = xdrlib.Packer()

    def assertRaisesConversion(self, *args):
        self.assertRaises(xdrlib.ConversionError, *args)

    def test_pack_int(self):
        self.assertRaisesConversion(self.packer.pack_int, 'string')


            

Reported by Pylint.

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

Line: 58 Column: 5

                  def setUp(self):
        self.packer = xdrlib.Packer()

    def assertRaisesConversion(self, *args):
        self.assertRaises(xdrlib.ConversionError, *args)

    def test_pack_int(self):
        self.assertRaisesConversion(self.packer.pack_int, 'string')


            

Reported by Pylint.

Modules/_testcapimodule.c
15 issues
There is an unknown macro here somewhere. Configuration is required. If Py_END_ALLOW_THREADS is a macro then please configure it.
Error

Line: 3623

                     in pydebug mode, since that's where the infinite loop was in
       the first place. */
    PyThreadState_Get();
    Py_END_ALLOW_THREADS
    return NULL;
}

/* To run some code in a sub-interpreter. */
static PyObject *

            

Reported by Cppcheck.

sprintf - Does not check for buffer overflows
Security

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

              #undef FAIL
#define FAIL(x) \
        { \
        sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \
            x, known->module, known->attribute); \
        error = buffer; \
        goto exit; \
        } \


            

Reported by FlawFinder.

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

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

                          PyErr_SetString(PyExc_ValueError, "string too long");
            return NULL;
        }
        strcpy(ob->structmembers.inplace_member, s);
    }
    else {
        strcpy(ob->structmembers.inplace_member, "");
    }
    return (PyObject *)ob;

            

Reported by FlawFinder.

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

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

                  PyObject *sub_keywords;

    Py_ssize_t i, size;
    char *keywords[8 + 1]; /* space for NULL at end */
    PyObject *o;
    PyObject *converted[8];

    int result;
    PyObject *return_value = NULL;

            

Reported by FlawFinder.

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

Line: 1979 Column: 11 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

              test_widechar(PyObject *self, PyObject *Py_UNUSED(ignored))
{
#if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
    const wchar_t wtext[2] = {(wchar_t)0x10ABCDu};
    size_t wtextlen = 1;
    const wchar_t invalid[1] = {(wchar_t)0x110000u};
#else
    const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu};
    size_t wtextlen = 2;

            

Reported by FlawFinder.

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

Line: 1981 Column: 11 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

              #if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
    const wchar_t wtext[2] = {(wchar_t)0x10ABCDu};
    size_t wtextlen = 1;
    const wchar_t invalid[1] = {(wchar_t)0x110000u};
#else
    const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu};
    size_t wtextlen = 2;
#endif
    PyObject *wide, *utf8;

            

Reported by FlawFinder.

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

Line: 1983 Column: 11 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

                  size_t wtextlen = 1;
    const wchar_t invalid[1] = {(wchar_t)0x110000u};
#else
    const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu};
    size_t wtextlen = 2;
#endif
    PyObject *wide, *utf8;

    wide = PyUnicode_FromWideChar(wtext, wtextlen);

            

Reported by FlawFinder.

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

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

                  if (u == NULL)
        return NULL;

    memcpy(PyUnicode_AS_UNICODE(u), data, len * sizeof(Py_UNICODE));

    if (len > 0) { /* The empty string is always ready. */
        assert(!PyUnicode_IS_READY(u));
    }


            

Reported by FlawFinder.

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

Line: 3185 Column: 16 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

                      /* yeah, ordinarily I wouldn't do this either,
           but it's fine for this test harness.
        */
        static char buffer[256];
#undef FAIL
#define FAIL(x) \
        { \
        sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \
            x, known->module, known->attribute); \

            

Reported by FlawFinder.

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

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

              {
    PyTypeObject *type = &_PyBytesIOBuffer_Type;
    PyObject *b;
    char *dummy[1];
    int ret, match;

    /* PyBuffer_FillInfo() */
    ret = PyBuffer_FillInfo(NULL, NULL, dummy, 1, 0, PyBUF_SIMPLE);
    match = PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_BufferError);

            

Reported by FlawFinder.

Lib/xml/dom/minicompat.py
15 issues
Unused argument 'index'
Error

Line: 87 Column: 20

                      NL.extend(other)
        return NL

    def item(self, index):
        return None

    def _get_length(self):
        return 0


            

Reported by Pylint.

Redefining built-in 'set'
Error

Line: 103 Column: 5

              
def defproperty(klass, name, doc):
    get = getattr(klass, ("_get_" + name))
    def set(self, value, name=name):
        raise xml.dom.NoModificationAllowedErr(
            "attempt to modify read-only attribute " + repr(name))
    assert not hasattr(klass, "_set_" + name), \
           "expected not to find _set_" + name
    prop = property(get, set, doc=doc)

            

Reported by Pylint.

Missing class docstring
Error

Line: 50 Column: 1

              StringTypes = (str,)


class NodeList(list):
    __slots__ = ()

    def item(self, index):
        if 0 <= index < len(self):
            return self[index]

            

Reported by Pylint.

Either all return statements in a function should return an expression, or none of them should.
Error

Line: 53 Column: 5

              class NodeList(list):
    __slots__ = ()

    def item(self, index):
        if 0 <= index < len(self):
            return self[index]

    def _get_length(self):
        return len(self)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 53 Column: 5

              class NodeList(list):
    __slots__ = ()

    def item(self, index):
        if 0 <= index < len(self):
            return self[index]

    def _get_length(self):
        return len(self)

            

Reported by Pylint.

Method could be a function
Error

Line: 60 Column: 5

                  def _get_length(self):
        return len(self)

    def _set_length(self, value):
        raise xml.dom.NoModificationAllowedErr(
            "attempt to modify read-only attribute 'length'")

    length = property(_get_length, _set_length,
                      doc="The number of nodes in the NodeList.")

            

Reported by Pylint.

Missing class docstring
Error

Line: 74 Column: 1

                      self[:] = state


class EmptyNodeList(tuple):
    __slots__ = ()

    def __add__(self, other):
        NL = NodeList()
        NL.extend(other)

            

Reported by Pylint.

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

Line: 78 Column: 9

                  __slots__ = ()

    def __add__(self, other):
        NL = NodeList()
        NL.extend(other)
        return NL

    def __radd__(self, other):
        NL = NodeList()

            

Reported by Pylint.

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

Line: 83 Column: 9

                      return NL

    def __radd__(self, other):
        NL = NodeList()
        NL.extend(other)
        return NL

    def item(self, index):
        return None

            

Reported by Pylint.

Method could be a function
Error

Line: 87 Column: 5

                      NL.extend(other)
        return NL

    def item(self, index):
        return None

    def _get_length(self):
        return 0


            

Reported by Pylint.

Tools/c-analyzer/c_analyzer/__init__.py
15 issues
No name 'datafiles' in module '__init__'
Error

Line: 13 Column: 1

                  filter_by_kind,
    group_by_kinds,
)
from . import (
    analyze as _analyze,
    datafiles as _datafiles,
)
from .info import Analysis


            

Reported by Pylint.

Unable to import '__init__.info'
Error

Line: 17 Column: 1

                  analyze as _analyze,
    datafiles as _datafiles,
)
from .info import Analysis


def analyze(filenmes, **kwargs):
    results = iter_analyis_results(filenames, **kwargs)
    return Analysis.from_results(results)

            

Reported by Pylint.

Undefined variable 'iter_analyis_results'
Error

Line: 21 Column: 15

              

def analyze(filenmes, **kwargs):
    results = iter_analyis_results(filenames, **kwargs)
    return Analysis.from_results(results)


def iter_analysis_results(filenmes, *,
                          known=None,

            

Reported by Pylint.

Undefined variable 'filenames'
Error

Line: 21 Column: 36

              

def analyze(filenmes, **kwargs):
    results = iter_analyis_results(filenames, **kwargs)
    return Analysis.from_results(results)


def iter_analysis_results(filenmes, *,
                          known=None,

            

Reported by Pylint.

Undefined variable 'filenames'
Error

Line: 29 Column: 24

                                        known=None,
                          **kwargs
                          ):
    decls = iter_decls(filenames, **kwargs)
    yield from analyze_decls(decls, known)


def iter_decls(filenames, *,
               kinds=None,

            

Reported by Pylint.

Module import itself
Error

Line: 13 Column: 1

                  filter_by_kind,
    group_by_kinds,
)
from . import (
    analyze as _analyze,
    datafiles as _datafiles,
)
from .info import Analysis


            

Reported by Pylint.

Module import itself
Error

Line: 13 Column: 1

                  filter_by_kind,
    group_by_kinds,
)
from . import (
    analyze as _analyze,
    datafiles as _datafiles,
)
from .info import Analysis


            

Reported by Pylint.

Unused argument 'filenmes'
Error

Line: 20 Column: 13

              from .info import Analysis


def analyze(filenmes, **kwargs):
    results = iter_analyis_results(filenames, **kwargs)
    return Analysis.from_results(results)


def iter_analysis_results(filenmes, *,

            

Reported by Pylint.

Unused argument 'filenmes'
Error

Line: 25 Column: 27

                  return Analysis.from_results(results)


def iter_analysis_results(filenmes, *,
                          known=None,
                          **kwargs
                          ):
    decls = iter_decls(filenames, **kwargs)
    yield from analyze_decls(decls, known)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from c_parser import (
    parse_files as _parse_files,
)
from c_parser.info import (
    KIND,
    TypeDeclaration,
    resolve_parsed,
)
from c_parser.match import (

            

Reported by Pylint.

Lib/tkinter/test/test_ttk/test_style.py
15 issues
Module 'sys' has no 'getwindowsversion' member
Error

Line: 141 Column: 33

                                  if support.verbose >= 2:
                        print('configure', theme, name, default)
                    if (theme in ('vista', 'xpnative')
                            and sys.getwindowsversion()[:2] == (6, 1)):
                        # Fails on the Windows 7 buildbot
                        continue
                    newname = f'C.{name}'
                    self.assertEqual(style.configure(newname), None)
                    style.configure(newname, **default)

            

Reported by Pylint.

Module 'sys' has no 'getwindowsversion' member
Error

Line: 167 Column: 33

                                  if support.verbose >= 2:
                        print('map', theme, name, default)
                    if (theme in ('vista', 'xpnative')
                            and sys.getwindowsversion()[:2] == (6, 1)):
                        # Fails on the Windows 7 buildbot
                        continue
                    newname = f'C.{name}'
                    self.assertEqual(style.map(newname), {})
                    style.map(newname, **default)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import unittest
import sys
import tkinter
from tkinter import ttk
from test import support
from test.support import requires, run_unittest
from tkinter.test.support import AbstractTkTest

requires('gui')

            

Reported by Pylint.

Imports from package tkinter are not grouped
Error

Line: 7 Column: 1

              from tkinter import ttk
from test import support
from test.support import requires, run_unittest
from tkinter.test.support import AbstractTkTest

requires('gui')

CLASS_NAMES = [
    '.', 'ComboboxPopdownFrame', 'Heading',

            

Reported by Pylint.

Missing class docstring
Error

Line: 21 Column: 1

                  'Vertical.TProgressbar', 'Vertical.TScale'
]

class StyleTest(AbstractTkTest, unittest.TestCase):

    def setUp(self):
        super().setUp()
        self.style = ttk.Style(self.root)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 28 Column: 5

                      self.style = ttk.Style(self.root)


    def test_configure(self):
        style = self.style
        style.configure('TButton', background='yellow')
        self.assertEqual(style.configure('TButton', 'background'),
            'yellow')
        self.assertIsInstance(style.configure('TButton'), dict)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 36 Column: 5

                      self.assertIsInstance(style.configure('TButton'), dict)


    def test_map(self):
        style = self.style

        # Single state
        for states in ['active'], [('active',)]:
            with self.subTest(states=states):

            

Reported by Pylint.

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

Line: 45 Column: 17

                              style.map('TButton', background=[(*states, 'white')])
                expected = [('active', 'white')]
                self.assertEqual(style.map('TButton', 'background'), expected)
                m = style.map('TButton')
                self.assertIsInstance(m, dict)
                self.assertEqual(m['background'], expected)

        # Multiple states
        for states in ['pressed', '!disabled'], ['pressed !disabled'], [('pressed', '!disabled')]:

            

Reported by Pylint.

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

Line: 55 Column: 17

                              style.map('TButton', background=[(*states, 'black')])
                expected = [('pressed', '!disabled', 'black')]
                self.assertEqual(style.map('TButton', 'background'), expected)
                m = style.map('TButton')
                self.assertIsInstance(m, dict)
                self.assertEqual(m['background'], expected)

        # Default state
        for states in [], [''], [()]:

            

Reported by Pylint.

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

Line: 65 Column: 17

                              style.map('TButton', background=[(*states, 'grey')])
                expected = [('grey',)]
                self.assertEqual(style.map('TButton', 'background'), expected)
                m = style.map('TButton')
                self.assertIsInstance(m, dict)
                self.assertEqual(m['background'], expected)


    def test_lookup(self):

            

Reported by Pylint.

Modules/fcntlmodule.c
15 issues
Uninitialized variable: ret
Error

Line: 75 CWE codes: 908

                              Py_BEGIN_ALLOW_THREADS
                ret = fcntl(fd, code, buf);
                Py_END_ALLOW_THREADS
            } while (ret == -1 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
            if (ret < 0) {
                return !async_err ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
            }
            return PyBytes_FromStringAndSize(buf, len);
        }

            

Reported by Cppcheck.

Uninitialized variable: ret
Error

Line: 76 CWE codes: 908

                              ret = fcntl(fd, code, buf);
                Py_END_ALLOW_THREADS
            } while (ret == -1 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
            if (ret < 0) {
                return !async_err ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
            }
            return PyBytes_FromStringAndSize(buf, len);
        }


            

Reported by Cppcheck.

Uninitialized variable: ret
Error

Line: 96 CWE codes: 908

                      Py_BEGIN_ALLOW_THREADS
        ret = fcntl(fd, code, (int)int_arg);
        Py_END_ALLOW_THREADS
    } while (ret == -1 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
    if (ret < 0) {
        return !async_err ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
    }
    return PyLong_FromLong((long)ret);
}

            

Reported by Cppcheck.

Uninitialized variable: ret
Error

Line: 212 CWE codes: 908

                              memcpy(str, buf, len);
            }
            PyBuffer_Release(&pstr); /* No further access to str below this point */
            if (ret < 0) {
                PyErr_SetFromErrno(PyExc_OSError);
                return NULL;
            }
            if (mutate_arg) {
                return PyLong_FromLong(ret);

            

Reported by Cppcheck.

Uninitialized variable: ret
Error

Line: 324 CWE codes: 908

                          Py_BEGIN_ALLOW_THREADS
            ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
            Py_END_ALLOW_THREADS
        } while (ret == -1 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
    }
#endif /* HAVE_FLOCK */
    if (ret < 0) {
        return !async_err ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
    }

            

Reported by Cppcheck.

Uninitialized variable: ret
Error

Line: 327 CWE codes: 908

                      } while (ret == -1 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
    }
#endif /* HAVE_FLOCK */
    if (ret < 0) {
        return !async_err ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
    }
    Py_RETURN_NONE;
}


            

Reported by Cppcheck.

Uninitialized variable: ret
Error

Line: 428 CWE codes: 908

                          Py_BEGIN_ALLOW_THREADS
            ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
            Py_END_ALLOW_THREADS
        } while (ret == -1 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
    }
    if (ret < 0) {
        return !async_err ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
    }
    Py_RETURN_NONE;

            

Reported by Cppcheck.

Uninitialized variable: ret
Error

Line: 430 CWE codes: 908

                          Py_END_ALLOW_THREADS
        } while (ret == -1 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
    }
    if (ret < 0) {
        return !async_err ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
    }
    Py_RETURN_NONE;
}


            

Reported by Cppcheck.

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

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

                  int ret;
    char *str;
    Py_ssize_t len;
    char buf[1024];
    int async_err = 0;

    if (PySys_Audit("fcntl.fcntl", "iiO", fd, code, arg ? arg : Py_None) < 0) {
        return NULL;
    }

            

Reported by FlawFinder.

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

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

                                              "fcntl string arg too long");
                return NULL;
            }
            memcpy(buf, str, len);
            do {
                Py_BEGIN_ALLOW_THREADS
                ret = fcntl(fd, code, buf);
                Py_END_ALLOW_THREADS
            } while (ret == -1 && errno == EINTR && !(async_err = PyErr_CheckSignals()));

            

Reported by FlawFinder.

Lib/test/test_tools/test_pathfix.py
15 issues
Unused support imported from test
Error

Line: 5 Column: 1

              import subprocess
import sys
import unittest
from test import support
from test.support import os_helper
from test.test_tools import scriptsdir, skip_if_missing


# need Tools/script/ directory: skip if run on Python installed on the system

            

Reported by Pylint.

Using subprocess.run without explicitly set `check` is not recommended.
Error

Line: 35 Column: 16

                          f.write(f'{shebang}\n' + 'print("Hello world")\n')

        encoding = sys.getfilesystemencoding()
        proc = subprocess.run(
            [sys.executable, self.script,
             *pathfix_flags, '-n', pathfix_arg],
            env={**os.environ, 'PYTHONIOENCODING': encoding},
            capture_output=True)


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import os
import subprocess
import sys
import unittest
from test import support
from test.support import os_helper
from test.test_tools import scriptsdir, skip_if_missing



            

Reported by Pylint.

Consider possible security implications associated with subprocess module.
Security blacklist

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

              import os
import subprocess
import sys
import unittest
from test import support
from test.support import os_helper
from test.test_tools import scriptsdir, skip_if_missing



            

Reported by Bandit.

Missing class docstring
Error

Line: 14 Column: 1

              skip_if_missing()


class TestPathfixFunctional(unittest.TestCase):
    script = os.path.join(scriptsdir, 'pathfix.py')

    def setUp(self):
        self.addCleanup(os_helper.unlink, os_helper.TESTFN)


            

Reported by Pylint.

Too many arguments (7/5)
Error

Line: 20 Column: 5

                  def setUp(self):
        self.addCleanup(os_helper.unlink, os_helper.TESTFN)

    def pathfix(self, shebang, pathfix_flags, exitcode=0, stdout='', stderr='',
                directory=''):
        if directory:
            # bpo-38347: Test filename should contain lowercase, uppercase,
            # "-", "_" and digits.
            filename = os.path.join(directory, 'script-A_1.py')

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 20 Column: 5

                  def setUp(self):
        self.addCleanup(os_helper.unlink, os_helper.TESTFN)

    def pathfix(self, shebang, pathfix_flags, exitcode=0, stdout='', stderr='',
                directory=''):
        if directory:
            # bpo-38347: Test filename should contain lowercase, uppercase,
            # "-", "_" and digits.
            filename = os.path.join(directory, 'script-A_1.py')

            

Reported by Pylint.

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

Line: 31 Column: 54

                          filename = os_helper.TESTFN
            pathfix_arg = filename

        with open(filename, 'w', encoding='utf8') as f:
            f.write(f'{shebang}\n' + 'print("Hello world")\n')

        encoding = sys.getfilesystemencoding()
        proc = subprocess.run(
            [sys.executable, self.script,

            

Reported by Pylint.

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

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

                          f.write(f'{shebang}\n' + 'print("Hello world")\n')

        encoding = sys.getfilesystemencoding()
        proc = subprocess.run(
            [sys.executable, self.script,
             *pathfix_flags, '-n', pathfix_arg],
            env={**os.environ, 'PYTHONIOENCODING': encoding},
            capture_output=True)


            

Reported by Bandit.

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

Line: 47 Column: 54

                      self.assertEqual(proc.stdout.decode(encoding), stdout.replace('\n', os.linesep), proc)
        self.assertEqual(proc.stderr.decode(encoding), stderr.replace('\n', os.linesep), proc)

        with open(filename, 'r', encoding='utf8') as f:
            output = f.read()

        lines = output.split('\n')
        self.assertEqual(lines[1:], ['print("Hello world")', ''])
        new_shebang = lines[0]

            

Reported by Pylint.

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

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

                          *str++ = sep;
        }
        len = wcslen(path);
        memcpy(str, path, len * sizeof(wchar_t));
        str += len;
    }
    *str = L'\0';

    return text;

            

Reported by FlawFinder.

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

Line: 229 Column: 9 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

                  SET_ITEM_STR(base_executable);

    {
        wchar_t py3path[MAX_PATH];
        HMODULE hPython3 = GetModuleHandleW(PY3_DLLNAME);
        PyObject *obj;
        if (hPython3
            && GetModuleFileNameW(hPython3, py3path, Py_ARRAY_LENGTH(py3path)))
        {

            

Reported by FlawFinder.

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

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

                      if (path == NULL) {
            return _PyStatus_NO_MEMORY();
        }
        memcpy(path, sys_path, path_len * sizeof(wchar_t));
        path[path_len] = L'\0';

        PyStatus status = PyWideStringList_Append(&config->module_search_paths, path);
        PyMem_RawFree(path);
        if (_PyStatus_EXCEPTION(status)) {

            

Reported by FlawFinder.

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

Line: 638 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 n = 0;

#ifdef HAVE_REALPATH
    wchar_t fullpath[MAXPATHLEN];
#elif defined(MS_WINDOWS)
    wchar_t fullpath[MAX_PATH];
#endif

    if (have_module_arg) {

            

Reported by FlawFinder.

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

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

              #ifdef HAVE_REALPATH
    wchar_t fullpath[MAXPATHLEN];
#elif defined(MS_WINDOWS)
    wchar_t fullpath[MAX_PATH];
#endif

    if (have_module_arg) {
#if defined(HAVE_REALPATH) || defined(MS_WINDOWS)
        if (!_Py_wgetcwd(fullpath, Py_ARRAY_LENGTH(fullpath))) {

            

Reported by FlawFinder.

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

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

                  }

#ifdef HAVE_READLINK
    wchar_t link[MAXPATHLEN + 1];
    int nr = 0;
    wchar_t path0copy[2 * MAXPATHLEN + 1];

    if (have_script_arg) {
        nr = _Py_wreadlink(path0, link, Py_ARRAY_LENGTH(link));

            

Reported by FlawFinder.

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

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

              #ifdef HAVE_READLINK
    wchar_t link[MAXPATHLEN + 1];
    int nr = 0;
    wchar_t path0copy[2 * MAXPATHLEN + 1];

    if (have_script_arg) {
        nr = _Py_wreadlink(path0, link, Py_ARRAY_LENGTH(link));
    }
    if (nr > 0) {

            

Reported by FlawFinder.

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

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

              {
    *value_p = NULL;

    char buffer[MAXPATHLEN * 2 + 1];  /* allow extra for key, '=', etc. */
    buffer[Py_ARRAY_LENGTH(buffer)-1] = '\0';

    while (!feof(env_file)) {
        char * p = fgets(buffer, Py_ARRAY_LENGTH(buffer) - 1, env_file);


            

Reported by FlawFinder.

wcslen - 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: 120 Column: 16 CWE codes: 126

                      if (i != 0) {
            len++;
        }
        len += wcslen(list->items[i]);
    }

    wchar_t *text = PyMem_RawMalloc(len * sizeof(wchar_t));
    if (text == NULL) {
        return NULL;

            

Reported by FlawFinder.

wcslen - 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: 133 Column: 15 CWE codes: 126

                      if (i != 0) {
            *str++ = sep;
        }
        len = wcslen(path);
        memcpy(str, path, len * sizeof(wchar_t));
        str += len;
    }
    *str = L'\0';


            

Reported by FlawFinder.

Modules/cjkcodecs/multibytecodec.c
15 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

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

                  retstrsize = PyBytes_GET_SIZE(retstr);
    if (retstrsize > 0) {
        REQUIRE_ENCODEBUFFER(buf, retstrsize);
        memcpy(buf->outbuf, PyBytes_AS_STRING(retstr), retstrsize);
        buf->outbuf += retstrsize;
    }

    newpos = PyLong_AsSsize_t(PyTuple_GET_ITEM(retobj, 1));
    if (newpos < 0 && !PyErr_Occurred())

            

Reported by FlawFinder.

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

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

                          PyErr_SetString(PyExc_UnicodeError, "pending buffer overflow");
            return -1;
    }
    memcpy(ctx->pending + ctx->pendingsize, buf->inbuf, npendings);
    ctx->pendingsize += npendings;
    return 0;
}

static int

            

Reported by FlawFinder.

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

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

                     array is used to avoid different compilers generating different
       values for the same state, e.g. as a result of struct padding.
    */
    unsigned char statebytes[1 + MAXENCPENDING*4 + sizeof(self->state.c)];
    Py_ssize_t statesize;
    const char *pendingbuffer = NULL;
    Py_ssize_t pendingsize;

    if (self->pending != NULL) {

            

Reported by FlawFinder.

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

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

                          return NULL;
        }
        statebytes[0] = (unsigned char)pendingsize;
        memcpy(statebytes + 1, pendingbuffer, pendingsize);
        statesize = 1 + pendingsize;
    } else {
        statebytes[0] = 0;
        statesize = 1;
    }

            

Reported by FlawFinder.

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

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

                      statebytes[0] = 0;
        statesize = 1;
    }
    memcpy(statebytes+statesize, self->state.c,
           sizeof(self->state.c));
    statesize += sizeof(self->state.c);

    return (PyObject *)_PyLong_FromByteArray(statebytes, statesize,
                                             1 /* little-endian */ ,

            

Reported by FlawFinder.

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

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

              /*[clinic end generated code: output=4e5e98ac1f4039ca input=c80fb5830d4d2f76]*/
{
    PyObject *pending = NULL;
    unsigned char statebytes[1 + MAXENCPENDING*4 + sizeof(self->state.c)];

    if (_PyLong_AsByteArray(statelong, statebytes, sizeof(statebytes),
                            1 /* little-endian */ ,
                            0 /* unsigned */ ) < 0) {
        goto errorexit;

            

Reported by FlawFinder.

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

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

              /*[clinic end generated code: output=b4125d8f537a253f input=930f06760707b6ea]*/
{
    /* Longest output: 4 bytes (b'\x0F\x1F(B') with ISO 2022 */
    unsigned char buffer[4], *outbuf;
    Py_ssize_t r;
    if (self->codec->encreset != NULL) {
        outbuf = buffer;
        r = self->codec->encreset(&self->state, self->codec->config,
                                  &outbuf, sizeof(buffer));

            

Reported by FlawFinder.

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

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

                          PyErr_NoMemory();
            goto errorexit;
        }
        memcpy(wdata, self->pending, self->pendingsize);
        memcpy(wdata + self->pendingsize, data, size);
        self->pendingsize = 0;
    }

    if (decoder_prepare_buffer(&buf, wdata, wsize) != 0)

            

Reported by FlawFinder.

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

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

                          goto errorexit;
        }
        memcpy(wdata, self->pending, self->pendingsize);
        memcpy(wdata + self->pendingsize, data, size);
        self->pendingsize = 0;
    }

    if (decoder_prepare_buffer(&buf, wdata, wsize) != 0)
        goto errorexit;

            

Reported by FlawFinder.

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

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

                      if (multibytecodec_decerror(self->codec, &self->state,
                        &buf, self->errors, MBERR_TOOFEW)) {
            /* recover the original pending buffer */
            memcpy(self->pending, wdata, origpending);
            self->pendingsize = origpending;
            goto errorexit;
        }
    }


            

Reported by FlawFinder.

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

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

                      PyErr_NoMemory();
        return NULL;
    }
    strcpy(copied, str);
    return copied;
}

static PyInterpreterState *
_get_current(void)

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 489 Column: 9 CWE codes: 362

              typedef struct _channelend {
    struct _channelend *next;
    int64_t interp;
    int open;
} _channelend;

static _channelend *
_channelend_new(int64_t interp)
{

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 620 Column: 19 CWE codes: 362

                  _channelend *end = _channelend_find(send ? ends->send : ends->recv,
                                        interp, &prev);
    if (end != NULL) {
        if (!end->open) {
            PyErr_SetString(ChannelClosedError, "channel already closed");
            return -1;
        }
        // already associated
        return 0;

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 716 Column: 9 CWE codes: 362

                  PyThread_type_lock mutex;
    _channelqueue *queue;
    _channelends *ends;
    int open;
    struct _channel_closing *closing;
} _PyChannelState;

static _PyChannelState *
_channel_new(void)

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 770 Column: 16 CWE codes: 362

                  int res = -1;
    PyThread_acquire_lock(chan->mutex, WAIT_LOCK);

    if (!chan->open) {
        PyErr_SetString(ChannelClosedError, "channel closed");
        goto done;
    }
    if (_channelends_associate(chan->ends, interp, 1) != 0) {
        goto done;

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 794 Column: 16 CWE codes: 362

                  _PyCrossInterpreterData *data = NULL;
    PyThread_acquire_lock(chan->mutex, WAIT_LOCK);

    if (!chan->open) {
        PyErr_SetString(ChannelClosedError, "channel closed");
        goto done;
    }
    if (_channelends_associate(chan->ends, interp, 0) != 0) {
        goto done;

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 821 Column: 16 CWE codes: 362

                  PyThread_acquire_lock(chan->mutex, WAIT_LOCK);

    int res = -1;
    if (!chan->open) {
        PyErr_SetString(ChannelClosedError, "channel already closed");
        goto done;
    }

    if (_channelends_close_interpreter(chan->ends, interp, end) != 0) {

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 843 Column: 16 CWE codes: 362

                  int res = -1;
    PyThread_acquire_lock(chan->mutex, WAIT_LOCK);

    if (!chan->open) {
        PyErr_SetString(ChannelClosedError, "channel already closed");
        goto done;
    }

    if (!force && chan->queue->count > 0) {

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 980 Column: 42 CWE codes: 362

                      PyErr_Format(ChannelNotFoundError, "channel %" PRId64 " not found", id);
        goto done;
    }
    if (ref->chan == NULL || !ref->chan->open) {
        PyErr_Format(ChannelClosedError, "channel %" PRId64 " closed", id);
        goto done;
    }

    if (pmutex != NULL) {

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 1406 Column: 33 CWE codes: 362

                  _channelend *end = _channelend_find(send ? chan->ends->send : chan->ends->recv,
                                        interp, NULL);

    return (end != NULL && end->open);
}

/* ChannelID class */

static PyTypeObject ChannelIDtype;

            

Reported by FlawFinder.