The following issues were found

Tools/c-analyzer/check-c-globals.py
11 issues
Undefined variable 'argv'
Error

Line: 25 Column: 9

                  cmd = 'check'
    verbosity, traceback_cm = process_args_by_key(
        args,
        argv,
        processors,
        ['verbosity', 'traceback_cm'],
    )

    return cmd, ns, verbosity, traceback_cm

            

Reported by Pylint.

Redefining name 'cmd' from outer scope (line 33)
Error

Line: 22 Column: 5

                  args = parser.parse_args()
    ns = vars(args)

    cmd = 'check'
    verbosity, traceback_cm = process_args_by_key(
        args,
        argv,
        processors,
        ['verbosity', 'traceback_cm'],

            

Reported by Pylint.

Redefining name 'traceback_cm' from outer scope (line 33)
Error

Line: 23 Column: 16

                  ns = vars(args)

    cmd = 'check'
    verbosity, traceback_cm = process_args_by_key(
        args,
        argv,
        processors,
        ['verbosity', 'traceback_cm'],
    )

            

Reported by Pylint.

Redefining name 'verbosity' from outer scope (line 33)
Error

Line: 23 Column: 5

                  ns = vars(args)

    cmd = 'check'
    verbosity, traceback_cm = process_args_by_key(
        args,
        argv,
        processors,
        ['verbosity', 'traceback_cm'],
    )

            

Reported by Pylint.

Module name "check-c-globals" doesn't conform to snake_case naming style
Error

Line: 1 Column: 1

              from cpython.__main__ import main, configure_logger


def parse_args():
    import argparse
    from c_common.scriptutil import (
        add_verbosity_cli,
        add_traceback_cli,
        process_args_by_key,

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from cpython.__main__ import main, configure_logger


def parse_args():
    import argparse
    from c_common.scriptutil import (
        add_verbosity_cli,
        add_traceback_cli,
        process_args_by_key,

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 4 Column: 1

              from cpython.__main__ import main, configure_logger


def parse_args():
    import argparse
    from c_common.scriptutil import (
        add_verbosity_cli,
        add_traceback_cli,
        process_args_by_key,

            

Reported by Pylint.

Import outside toplevel (argparse)
Error

Line: 5 Column: 5

              

def parse_args():
    import argparse
    from c_common.scriptutil import (
        add_verbosity_cli,
        add_traceback_cli,
        process_args_by_key,
    )

            

Reported by Pylint.

Import outside toplevel (c_common.scriptutil.add_verbosity_cli, c_common.scriptutil.add_traceback_cli, c_common.scriptutil.process_args_by_key)
Error

Line: 6 Column: 5

              
def parse_args():
    import argparse
    from c_common.scriptutil import (
        add_verbosity_cli,
        add_traceback_cli,
        process_args_by_key,
    )
    from cpython.__main__ import _cli_check

            

Reported by Pylint.

Import outside toplevel (cpython.__main__._cli_check)
Error

Line: 11 Column: 5

                      add_traceback_cli,
        process_args_by_key,
    )
    from cpython.__main__ import _cli_check
    parser = argparse.ArgumentParser()
    processors = [
        add_verbosity_cli(parser),
        add_traceback_cli(parser),
        _cli_check(parser, checks='<globals>'),

            

Reported by Pylint.

Lib/xml/etree/ElementInclude.py
11 issues
Attempted relative import beyond top-level package
Error

Line: 52 Column: 1

              ##

import copy
from . import ElementTree
from urllib.parse import urljoin

XINCLUDE = "{http://www.w3.org/2001/XInclude}"

XINCLUDE_INCLUDE = XINCLUDE + "include"

            

Reported by Pylint.

FIXME: this makes little sense with recursive includes
Error

Line: 154 Column: 3

                                  raise FatalIncludeError(
                        "cannot load %r as %r" % (href, parse)
                        )
                node = copy.copy(node)  # FIXME: this makes little sense with recursive includes
                _include(node, loader, href, max_depth - 1, _parent_hrefs)
                _parent_hrefs.remove(href)
                if e.tail:
                    node.tail = (node.tail or "") + e.tail
                elem[i] = node

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #
# ElementTree
# $Id: ElementInclude.py 3375 2008-02-13 08:05:08Z fredrik $
#
# limited xinclude support for element trees
#
# history:
# 2003-08-15 fl   created
# 2003-11-14 fl   fixed default loader

            

Reported by Pylint.

Module name "ElementInclude" doesn't conform to snake_case naming style
Error

Line: 1 Column: 1

              #
# ElementTree
# $Id: ElementInclude.py 3375 2008-02-13 08:05:08Z fredrik $
#
# limited xinclude support for element trees
#
# history:
# 2003-08-15 fl   created
# 2003-11-14 fl   fixed default loader

            

Reported by Pylint.

standard import "from urllib.parse import urljoin" should be placed before "from . import ElementTree"
Error

Line: 53 Column: 1

              
import copy
from . import ElementTree
from urllib.parse import urljoin

XINCLUDE = "{http://www.w3.org/2001/XInclude}"

XINCLUDE_INCLUDE = XINCLUDE + "include"
XINCLUDE_FALLBACK = XINCLUDE + "fallback"

            

Reported by Pylint.

Missing class docstring
Error

Line: 67 Column: 1

              ##
# Fatal include error.

class FatalIncludeError(SyntaxError):
    pass


class LimitedRecursiveIncludeError(FatalIncludeError):
    pass

            

Reported by Pylint.

Missing class docstring
Error

Line: 71 Column: 1

                  pass


class LimitedRecursiveIncludeError(FatalIncludeError):
    pass


##
# Default loader.  This loader reads an included resource from disk.

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 87 Column: 1

              #    or raise an OSError exception.
# @throws OSError If the loader fails to load the resource.

def default_loader(href, parse, encoding=None):
    if parse == "xml":
        with open(href, 'rb') as file:
            data = ElementTree.parse(file).getroot()
    else:
        if not encoding:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 116 Column: 1

              # @throws IOError If the function fails to load a given resource.
# @returns the node or its replacement if it was an XInclude node

def include(elem, loader=None, base_url=None,
            max_depth=DEFAULT_MAX_INCLUSION_DEPTH):
    if max_depth is None:
        max_depth = -1
    elif max_depth < 0:
        raise ValueError("expected non-negative depth or None for 'max_depth', got %r" % max_depth)

            

Reported by Pylint.

Too many branches (16/12)
Error

Line: 131 Column: 1

                  _include(elem, loader, base_url, max_depth, set())


def _include(elem, loader, base_url, max_depth, _parent_hrefs):
    # look for xinclude elements
    i = 0
    while i < len(elem):
        e = elem[i]
        if e.tag == XINCLUDE_INCLUDE:

            

Reported by Pylint.

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

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

                          PyErr_NoMemory();
            return -1;
        }
        strcpy(dst->format, src->format);
    }
    if (src->shape) {
        dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim);
        if (dst->shape == NULL) {
            PyErr_NoMemory();

            

Reported by FlawFinder.

sprintf - Does not check for buffer overflows
Security

Line: 582 Column: 13 CWE codes: 120
Suggestion: Use sprintf_s, snprintf, or vsnprintf

                              PyErr_NoMemory();
                return -1;
            }
            sprintf(buf, "%s:%s:", fieldfmt, fieldname);

            ptr = stgdict->format;
            if (dict->shape != NULL) {
                stgdict->format = _ctypes_alloc_format_string_with_shape(
                    dict->ndim, dict->shape, stgdict->format, buf);

            

Reported by FlawFinder.

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

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

              
    d = (char *)dst;
    s = (char *)src;
    memcpy(d + sizeof(PyDictObject),
           s + sizeof(PyDictObject),
           sizeof(StgDictObject) - sizeof(PyDictObject));

    Py_XINCREF(dst->proto);
    Py_XINCREF(dst->argtypes);

            

Reported by FlawFinder.

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

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

                          PyErr_NoMemory();
            return -1;
        }
        memcpy(dst->shape, src->shape,
               sizeof(Py_ssize_t) * src->ndim);
    }

    if (src->ffi_type_pointer.elements == NULL)
        return 0;

            

Reported by FlawFinder.

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

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

                      PyErr_NoMemory();
        return -1;
    }
    memcpy(dst->ffi_type_pointer.elements,
           src->ffi_type_pointer.elements,
           size);
    return 0;
}


            

Reported by FlawFinder.

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

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

                      memset(stgdict->ffi_type_pointer.elements, 0,
               sizeof(ffi_type *) * (basedict->length + len + 1));
        if (basedict->length > 0) {
            memcpy(stgdict->ffi_type_pointer.elements,
                   basedict->ffi_type_pointer.elements,
                   sizeof(ffi_type *) * (basedict->length));
        }
        ffi_ofs = basedict->length;
    } else {

            

Reported by FlawFinder.

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

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

                          memset(structs, 0, num_ffi_types * sizeof(ffi_type));
        }
        if (ffi_ofs && (basedict != NULL)) {
            memcpy(element_types,
                basedict->ffi_type_pointer.elements,
                ffi_ofs * sizeof(ffi_type *));
        }
        element_index = ffi_ofs;


            

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

                  res = _PyDict_SizeOf((PyDictObject *)self);
    res += sizeof(StgDictObject) - sizeof(PyDictObject);
    if (self->format)
        res += strlen(self->format) + 1;
    res += self->ndim * sizeof(Py_ssize_t);
    if (self->ffi_type_pointer.elements)
        res += (self->length + 1) * sizeof(ffi_type *);
    return PyLong_FromSsize_t(res);
}

            

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: 93 Column: 36 CWE codes: 126

                  Py_XINCREF(dst->checker);

    if (src->format) {
        dst->format = PyMem_Malloc(strlen(src->format) + 1);
        if (dst->format == NULL) {
            PyErr_NoMemory();
            return -1;
        }
        strcpy(dst->format, src->format);

            

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: 574 Column: 39 CWE codes: 126

                              return -1;
            }

            len = strlen(fieldname) + strlen(fieldfmt);

            buf = PyMem_Malloc(len + 2 + 1);
            if (buf == NULL) {
                Py_DECREF(pair);
                PyErr_NoMemory();

            

Reported by FlawFinder.

Lib/tkinter/commondialog.py
11 issues
Unused Frame imported from tkinter
Error

Line: 13 Column: 1

              
__all__ = ["Dialog"]

from tkinter import Frame, _get_temp_root, _destroy_temp_root


class Dialog:

    command = None

            

Reported by Pylint.

Unused argument 'widget'
Error

Line: 29 Column: 26

                  def _fixoptions(self):
        pass # hook

    def _fixresult(self, widget, result):
        return result # hook

    def show(self, **options):

        # update instance options

            

Reported by Pylint.

Access to a protected member _options of a client class
Error

Line: 45 Column: 47

                          master = _get_temp_root()
        try:
            self._test_callback(master)  # The function below is replaced for some tests.
            s = master.tk.call(self.command, *master._options(self.options))
            s = self._fixresult(master, s)
        finally:
            _destroy_temp_root(master)

        return s

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # base class for tk common dialogues
#
# this module provides a base class for accessing the common
# dialogues available in Tk 4.2 and newer.  use filedialog,
# colorchooser, and messagebox to access the individual
# dialogs.
#
# written by Fredrik Lundh, May 1997
#

            

Reported by Pylint.

Missing class docstring
Error

Line: 16 Column: 1

              from tkinter import Frame, _get_temp_root, _destroy_temp_root


class Dialog:

    command = None

    def __init__(self, master=None, **options):
        if master is None:

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 16 Column: 1

              from tkinter import Frame, _get_temp_root, _destroy_temp_root


class Dialog:

    command = None

    def __init__(self, master=None, **options):
        if master is None:

            

Reported by Pylint.

Method could be a function
Error

Line: 29 Column: 5

                  def _fixoptions(self):
        pass # hook

    def _fixresult(self, widget, result):
        return result # hook

    def show(self, **options):

        # update instance options

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 32 Column: 5

                  def _fixresult(self, widget, result):
        return result # hook

    def show(self, **options):

        # update instance options
        for k, v in options.items():
            self.options[k] = v


            

Reported by Pylint.

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

Line: 35 Column: 16

                  def show(self, **options):

        # update instance options
        for k, v in options.items():
            self.options[k] = v

        self._fixoptions()

        master = self.master

            

Reported by Pylint.

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

Line: 45 Column: 13

                          master = _get_temp_root()
        try:
            self._test_callback(master)  # The function below is replaced for some tests.
            s = master.tk.call(self.command, *master._options(self.options))
            s = self._fixresult(master, s)
        finally:
            _destroy_temp_root(master)

        return s

            

Reported by Pylint.

Lib/tkinter/messagebox.py
11 issues
Missing module docstring
Error

Line: 1 Column: 1

              # tk common message boxes
#
# this module provides an interface to the native message boxes
# available in Tk 4.2 and newer.
#
# written by Fredrik Lundh, May 1997
#

#

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 61 Column: 1

              #
# message dialog class

class Message(Dialog):
    "A message box"

    command  = "tk_messageBox"



            

Reported by Pylint.

More than one statement on a single line
Error

Line: 72 Column: 44

              
# Rename _icon and _type options to allow overriding them in options
def _show(title=None, message=None, _icon=None, _type=None, **options):
    if _icon and "icon" not in options:    options["icon"] = _icon
    if _type and "type" not in options:    options["type"] = _type
    if title:   options["title"] = title
    if message: options["message"] = message
    res = Message(**options).show()
    # In some Tcl installations, yes/no is converted into a boolean.

            

Reported by Pylint.

More than one statement on a single line
Error

Line: 73 Column: 44

              # Rename _icon and _type options to allow overriding them in options
def _show(title=None, message=None, _icon=None, _type=None, **options):
    if _icon and "icon" not in options:    options["icon"] = _icon
    if _type and "type" not in options:    options["type"] = _type
    if title:   options["title"] = title
    if message: options["message"] = message
    res = Message(**options).show()
    # In some Tcl installations, yes/no is converted into a boolean.
    if isinstance(res, bool):

            

Reported by Pylint.

More than one statement on a single line
Error

Line: 74 Column: 17

              def _show(title=None, message=None, _icon=None, _type=None, **options):
    if _icon and "icon" not in options:    options["icon"] = _icon
    if _type and "type" not in options:    options["type"] = _type
    if title:   options["title"] = title
    if message: options["message"] = message
    res = Message(**options).show()
    # In some Tcl installations, yes/no is converted into a boolean.
    if isinstance(res, bool):
        if res:

            

Reported by Pylint.

More than one statement on a single line
Error

Line: 75 Column: 17

                  if _icon and "icon" not in options:    options["icon"] = _icon
    if _type and "type" not in options:    options["type"] = _type
    if title:   options["title"] = title
    if message: options["message"] = message
    res = Message(**options).show()
    # In some Tcl installations, yes/no is converted into a boolean.
    if isinstance(res, bool):
        if res:
            return YES

            

Reported by Pylint.

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

Line: 108 Column: 5

              
def askokcancel(title=None, message=None, **options):
    "Ask if operation should proceed; return true if the answer is ok"
    s = _show(title, message, QUESTION, OKCANCEL, **options)
    return s == OK


def askyesno(title=None, message=None, **options):
    "Ask a question; return true if the answer is yes"

            

Reported by Pylint.

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

Line: 114 Column: 5

              
def askyesno(title=None, message=None, **options):
    "Ask a question; return true if the answer is yes"
    s = _show(title, message, QUESTION, YESNO, **options)
    return s == YES


def askyesnocancel(title=None, message=None, **options):
    "Ask a question; return true if the answer is yes, None if cancelled."

            

Reported by Pylint.

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

Line: 120 Column: 5

              
def askyesnocancel(title=None, message=None, **options):
    "Ask a question; return true if the answer is yes, None if cancelled."
    s = _show(title, message, QUESTION, YESNOCANCEL, **options)
    # s might be a Tcl index object, so convert it to a string
    s = str(s)
    if s == CANCEL:
        return None
    return s == YES

            

Reported by Pylint.

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

Line: 122 Column: 5

                  "Ask a question; return true if the answer is yes, None if cancelled."
    s = _show(title, message, QUESTION, YESNOCANCEL, **options)
    # s might be a Tcl index object, so convert it to a string
    s = str(s)
    if s == CANCEL:
        return None
    return s == YES



            

Reported by Pylint.

Lib/zoneinfo/_tzpath.py
11 issues
Using the global statement
Error

Line: 6 Column: 5

              

def reset_tzpath(to=None):
    global TZPATH

    tzpaths = to
    if tzpaths is not None:
        if isinstance(tzpaths, (str, bytes)):
            raise TypeError(

            

Reported by Pylint.

Using an f-string that does not have any interpolated variables
Error

Line: 12 Column: 17

                  if tzpaths is not None:
        if isinstance(tzpaths, (str, bytes)):
            raise TypeError(
                f"tzpaths must be a list or tuple, "
                + f"not {type(tzpaths)}: {tzpaths!r}"
            )

        if not all(map(os.path.isabs, tzpaths)):
            raise ValueError(_get_invalid_paths_message(tzpaths))

            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 133 Column: 16

                      try:
            with open(fpath, "rb") as f:
                return f.read(4) == b"TZif"
        except Exception:  # pragma: nocover
            return False

    for tz_root in TZPATH:
        if not os.path.exists(tz_root):
            continue

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import os
import sysconfig


def reset_tzpath(to=None):
    global TZPATH

    tzpaths = to
    if tzpaths is not None:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 5 Column: 1

              import sysconfig


def reset_tzpath(to=None):
    global TZPATH

    tzpaths = to
    if tzpaths is not None:
        if isinstance(tzpaths, (str, bytes)):

            

Reported by Pylint.

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

Line: 5 Column: 1

              import sysconfig


def reset_tzpath(to=None):
    global TZPATH

    tzpaths = to
    if tzpaths is not None:
        if isinstance(tzpaths, (str, bytes)):

            

Reported by Pylint.

Import outside toplevel (warnings)
Error

Line: 40 Column: 9

              
    # If anything has been filtered out, we will warn about it
    if len(new_tzpath) != len(raw_tzpath):
        import warnings

        msg = _get_invalid_paths_message(raw_tzpath)

        warnings.warn(
            "Invalid paths specified in PYTHONTZPATH environment variable. "

            

Reported by Pylint.

Too many branches (14/12)
Error

Line: 105 Column: 1

              del _TEST_PATH


def available_timezones():
    """Returns a set containing all available time zones.

    .. caution::

        This may attempt to open a large number of files, since the best way to

            

Reported by Pylint.

Import outside toplevel (importlib.resources)
Error

Line: 114 Column: 5

                      determine if a given file on the time zone search path is to open it
        and check for the "magic string" at the beginning.
    """
    from importlib import resources

    valid_zones = set()

    # Start with loading from the tzdata package if it exists: this has a
    # pre-assembled list of zones that only requires opening one file.

            

Reported by Pylint.

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

Line: 121 Column: 56

                  # Start with loading from the tzdata package if it exists: this has a
    # pre-assembled list of zones that only requires opening one file.
    try:
        with resources.open_text("tzdata", "zones") as f:
            for zone in f:
                zone = zone.strip()
                if zone:
                    valid_zones.add(zone)
    except (ImportError, FileNotFoundError):

            

Reported by Pylint.

Python/traceback.c
11 issues
strcpy - Does not check for buffer overflows when copying to destination [MS-banned]
Security

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

                          Py_DECREF(path);
            continue; /* Too long */
        }
        strcpy(namebuf, PyBytes_AS_STRING(path));
        Py_DECREF(path);
        if (strlen(namebuf) != (size_t)len)
            continue; /* v contains '\0' */
        if (len > 0 && namebuf[len-1] != SEP)
            namebuf[len++] = SEP;

            

Reported by FlawFinder.

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

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

                          continue; /* v contains '\0' */
        if (len > 0 && namebuf[len-1] != SEP)
            namebuf[len++] = SEP;
        strcpy(namebuf+len, tail);

        binary = _PyObject_CallMethodId(io, &PyId_open, "ss", namebuf, "rb");
        if (binary != NULL) {
            result = binary;
            goto finally;

            

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: 33 Column: 16 CWE codes: 362

              
_Py_IDENTIFIER(TextIOWrapper);
_Py_IDENTIFIER(close);
_Py_IDENTIFIER(open);
_Py_IDENTIFIER(path);

/*[clinic input]
class TracebackType "PyTracebackObject *" "&PyTraceback_Type"
[clinic start generated code]*/

            

Reported by FlawFinder.

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

Line: 391 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 *fob = NULL;
    PyObject *lineobj = NULL;
    PyObject *res;
    char buf[MAXPATHLEN+1];
    int kind;
    const void *data;

    /* open the file */
    if (filename == NULL)

            

Reported by FlawFinder.

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

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

                  }

    /* Write some spaces before the line */
    strcpy(buf, "          ");
    assert (strlen(buf) == 10);
    while (indent > 0) {
        if (indent < 10)
            buf[indent] = '\0';
        err = PyFile_WriteString(buf, f);

            

Reported by FlawFinder.

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

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

                  /* maximum number of characters required for output of %lld or %p.
       We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
       plus 1 for the null byte.  53/22 is an upper bound for log10(256). */
    char buffer[1 + (sizeof(size_t)*53-1) / 22 + 1];
    char *ptr, *end;

    end = &buffer[Py_ARRAY_LENGTH(buffer) - 1];
    ptr = end;
    *ptr = '\0';

            

Reported by FlawFinder.

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

Line: 932 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
_Py_DumpHexadecimal(int fd, uintptr_t value, Py_ssize_t width)
{
    char buffer[sizeof(uintptr_t) * 2 + 1], *ptr, *end;
    const Py_ssize_t size = Py_ARRAY_LENGTH(buffer) - 1;

    if (width > size)
        width = size;
    /* it's ok if width is negative */

            

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: 23 Column: 55 CWE codes: 126

              
#define OFF(x) offsetof(PyTracebackObject, x)

#define PUTS(fd, str) _Py_write_noraise(fd, str, (int)strlen(str))
#define MAX_STRING_LENGTH 500
#define MAX_FRAME_DEPTH 100
#define MAX_NTHREADS 100

/* Function from Parser/tokenizer.c */

            

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

                      tail = filepath;
    else
        tail++;
    taillen = strlen(tail);

    syspath = _PySys_GetObjectId(&PyId_path);
    if (syspath == NULL || !PyList_Check(syspath))
        goto error;
    npath = PyList_Size(syspath);

            

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: 356 Column: 13 CWE codes: 126

                      }
        strcpy(namebuf, PyBytes_AS_STRING(path));
        Py_DECREF(path);
        if (strlen(namebuf) != (size_t)len)
            continue; /* v contains '\0' */
        if (len > 0 && namebuf[len-1] != SEP)
            namebuf[len++] = SEP;
        strcpy(namebuf+len, tail);


            

Reported by FlawFinder.

Tools/demo/mcast.py
11 issues
Redefining name 'sender' from outer scope (line 33)
Error

Line: 76 Column: 15

              
    # Loop, printing any data we receive
    while True:
        data, sender = s.recvfrom(1500)
        while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's
        print(str(sender) + '  ' + repr(data))


if __name__ == '__main__':

            

Reported by Pylint.

Import "import time" should be placed at the top of the module
Error

Line: 19 Column: 1

              MYGROUP_6 = 'ff15:7079:7468:6f6e:6465:6d6f:6d63:6173'
MYTTL = 1 # Increase to reach other networks

import time
import struct
import socket
import sys

def main():

            

Reported by Pylint.

Import "import struct" should be placed at the top of the module
Error

Line: 20 Column: 1

              MYTTL = 1 # Increase to reach other networks

import time
import struct
import socket
import sys

def main():
    group = MYGROUP_6 if "-6" in sys.argv[1:] else MYGROUP_4

            

Reported by Pylint.

Import "import socket" should be placed at the top of the module
Error

Line: 21 Column: 1

              
import time
import struct
import socket
import sys

def main():
    group = MYGROUP_6 if "-6" in sys.argv[1:] else MYGROUP_4


            

Reported by Pylint.

Import "import sys" should be placed at the top of the module
Error

Line: 22 Column: 1

              import time
import struct
import socket
import sys

def main():
    group = MYGROUP_6 if "-6" in sys.argv[1:] else MYGROUP_4

    if "-s" in sys.argv[1:]:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 24 Column: 1

              import socket
import sys

def main():
    group = MYGROUP_6 if "-6" in sys.argv[1:] else MYGROUP_4

    if "-s" in sys.argv[1:]:
        sender(group)
    else:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 33 Column: 1

                      receiver(group)


def sender(group):
    addrinfo = socket.getaddrinfo(group, None)[0]

    s = socket.socket(addrinfo[0], socket.SOCK_DGRAM)

    # Set Time-to-live (optional)

            

Reported by Pylint.

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

Line: 36 Column: 5

              def sender(group):
    addrinfo = socket.getaddrinfo(group, None)[0]

    s = socket.socket(addrinfo[0], socket.SOCK_DGRAM)

    # Set Time-to-live (optional)
    ttl_bin = struct.pack('@i', MYTTL)
    if addrinfo[0] == socket.AF_INET: # IPv4
        s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 51 Column: 1

                      time.sleep(1)


def receiver(group):
    # Look up multicast group address in name server and find out IP version
    addrinfo = socket.getaddrinfo(group, None)[0]

    # Create a socket
    s = socket.socket(addrinfo[0], socket.SOCK_DGRAM)

            

Reported by Pylint.

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

Line: 56 Column: 5

                  addrinfo = socket.getaddrinfo(group, None)[0]

    # Create a socket
    s = socket.socket(addrinfo[0], socket.SOCK_DGRAM)

    # Allow multiple copies of this program on one machine
    # (not strictly needed)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)


            

Reported by Pylint.

PC/_msi.c
11 issues
strcpy - Does not check for buffer overflows when copying to destination [MS-banned]
Security

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

              {
    char *name = _tempnam("", "tmp");
    if ((name != NULL) && ((int)strlen(name) < cbTempName)) {
        strcpy(pszTempName, name);
        free(name);
        return TRUE;
    }

    if (name) free(name);

            

Reported by FlawFinder.

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

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

                  if (i > 0) {
        memcpy(ccab.szCabPath, cabname, i);
        ccab.szCabPath[i] = '\0';
        strcpy(ccab.szCab, cabname+i);
    } else {
        strcpy(ccab.szCabPath, ".\\");
        strcpy(ccab.szCab, cabname);
    }


            

Reported by FlawFinder.

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

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

                      strcpy(ccab.szCab, cabname+i);
    } else {
        strcpy(ccab.szCabPath, ".\\");
        strcpy(ccab.szCab, cabname);
    }

    hfci = FCICreate(&erf, cb_fileplaced, cb_alloc, cb_free,
        cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete,
        cb_gettempfile, &ccab, NULL);

            

Reported by FlawFinder.

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

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

                  }

    if (i > 0) {
        memcpy(ccab.szCabPath, cabname, i);
        ccab.szCabPath[i] = '\0';
        strcpy(ccab.szCab, cabname+i);
    } else {
        strcpy(ccab.szCabPath, ".\\");
        strcpy(ccab.szCab, cabname);

            

Reported by FlawFinder.

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

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

                      ccab.szCabPath[i] = '\0';
        strcpy(ccab.szCab, cabname+i);
    } else {
        strcpy(ccab.szCabPath, ".\\");
        strcpy(ccab.szCab, cabname);
    }

    hfci = FCICreate(&erf, cb_fileplaced, cb_alloc, cb_free,
        cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete,

            

Reported by FlawFinder.

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

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

              msierror(int status)
{
    int code;
    char buf[2000];
    char *res = buf;
    DWORD size = sizeof(buf);
    MSIHANDLE err = MsiGetLastErrorRecord();

    if (err == 0) {

            

Reported by FlawFinder.

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

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

                  UINT type;
    INT ival;
    FILETIME fval;
    char sbuf[1000];
    char *sval = sbuf;
    DWORD ssize = sizeof(sbuf);

    status = MsiSummaryInfoGetProperty(self->h, field, &type, &ival,
        &fval, sval, &ssize);

            

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: 54 Column: 47 CWE codes: 126

                      return NULL;
    }

    oresult = PyUnicode_FromWideChar(cresult, wcslen(cresult));
    RpcStringFreeW(&cresult);
    return oresult;

}


            

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: 162 Column: 33 CWE codes: 126

              static FNFCIGETTEMPFILE(cb_gettempfile)
{
    char *name = _tempnam("", "tmp");
    if ((name != NULL) && ((int)strlen(name) < cbTempName)) {
        strcpy(pszTempName, name);
        free(name);
        return TRUE;
    }


            

Reported by FlawFinder.

strncpy - Easily used incorrectly; doesn't always \0-terminate or check for invalid pointers [MS-banned]
Security

Line: 200 Column: 9 CWE codes: 120

                          Py_DECREF(result);
            return FALSE;
        }
        strncpy(pccab->szCab, PyBytes_AsString(result), sizeof(pccab->szCab));
        return TRUE;
    }
    return FALSE;
}


            

Reported by FlawFinder.

Lib/test/test_smtpnet.py
11 issues
Catching too general exception Exception
Error

Line: 17 Column: 16

                  with socket.create_connection((host, port)) as sock:
        try:
            sock = context.wrap_socket(sock, server_hostname=host)
        except Exception:
            return False
        else:
            sock.close()
            return True


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import unittest
from test import support
from test.support import import_helper
from test.support import socket_helper
import smtplib
import socket

ssl = import_helper.import_module("ssl")


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 12 Column: 1

              
support.requires("network")

def check_ssl_verifiy(host, port):
    context = ssl.create_default_context()
    with socket.create_connection((host, port)) as sock:
        try:
            sock = context.wrap_socket(sock, server_hostname=host)
        except Exception:

            

Reported by Pylint.

Missing class docstring
Error

Line: 24 Column: 1

                          return True


class SmtpTest(unittest.TestCase):
    testServer = 'smtp.gmail.com'
    remotePort = 587

    def test_connect_starttls(self):
        support.get_attribute(smtplib, 'SMTP_SSL')

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 28 Column: 5

                  testServer = 'smtp.gmail.com'
    remotePort = 587

    def test_connect_starttls(self):
        support.get_attribute(smtplib, 'SMTP_SSL')
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        with socket_helper.transient_internet(self.testServer):

            

Reported by Pylint.

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

Line: 37 Column: 13

                          server = smtplib.SMTP(self.testServer, self.remotePort)
            try:
                server.starttls(context=context)
            except smtplib.SMTPException as e:
                if e.args[0] == 'STARTTLS extension not supported by server.':
                    unittest.skip(e.args[0])
                else:
                    raise
            server.ehlo()

            

Reported by Pylint.

Missing class docstring
Error

Line: 46 Column: 1

                          server.quit()


class SmtpSSLTest(unittest.TestCase):
    testServer = 'smtp.gmail.com'
    remotePort = 465

    def test_connect(self):
        support.get_attribute(smtplib, 'SMTP_SSL')

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 50 Column: 5

                  testServer = 'smtp.gmail.com'
    remotePort = 465

    def test_connect(self):
        support.get_attribute(smtplib, 'SMTP_SSL')
        with socket_helper.transient_internet(self.testServer):
            server = smtplib.SMTP_SSL(self.testServer, self.remotePort)
            server.ehlo()
            server.quit()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 57 Column: 5

                          server.ehlo()
            server.quit()

    def test_connect_default_port(self):
        support.get_attribute(smtplib, 'SMTP_SSL')
        with socket_helper.transient_internet(self.testServer):
            server = smtplib.SMTP_SSL(self.testServer)
            server.ehlo()
            server.quit()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 64 Column: 5

                          server.ehlo()
            server.quit()

    def test_connect_using_sslcontext(self):
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        support.get_attribute(smtplib, 'SMTP_SSL')
        with socket_helper.transient_internet(self.testServer):

            

Reported by Pylint.