From b28f919007439b48a1d00d54134d7b020a683cda Mon Sep 17 00:00:00 2001
From: Max Bachmann <kontakt@maxbachmann.de>
Date: Sun, 26 Mar 2023 00:35:00 +0100
Subject: [PATCH] =?UTF-8?q?[3.11]=20gh-102281:=20Fix=20potential=20nullptr?=
 =?UTF-8?q?=20dereference=20+=20use=20of=20uninitia=E2=80=A6=20(#103040)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

[3.11] gh-102281: Fix potential nullptr dereference + use of uninitialized memory (gh-102282)
(cherry picked from commit afa6092ee4260bacf7bc11905466e4c3f8556cbb)
---
 .../2023-03-02-13-49-21.gh-issue-102281.QCuu2N.rst          | 1 +
 Modules/getpath.c                                           | 5 ++++-
 Python/fileutils.c                                          | 6 +++++-
 3 files changed, 10 insertions(+), 2 deletions(-)
 create mode 100644 Misc/NEWS.d/next/Core and Builtins/2023-03-02-13-49-21.gh-issue-102281.QCuu2N.rst

Bug-Upstream: https://github.com/python/cpython/issues/102281
Origin: upstream, https://github.com/python/cpython/commit/b28f919007439b48a1d00d54134d7b020a683cda

--- a/Modules/getpath.c
+++ b/Modules/getpath.c
@@ -452,7 +452,10 @@
             if (s) {
                 *s = L'\0';
             }
-            path2 = _Py_normpath(_Py_join_relfile(path, resolved), -1);
+            path2 = _Py_join_relfile(path, resolved);
+            if (path2) {
+                path2 = _Py_normpath(path2, -1);
+            }
             PyMem_RawFree((void *)path);
             path = path2;
         }
--- a/Python/fileutils.c
+++ b/Python/fileutils.c
@@ -2142,7 +2142,10 @@
     }
     assert(wcslen(dirname) < MAXPATHLEN);
     assert(wcslen(relfile) < MAXPATHLEN - wcslen(dirname));
-    join_relfile(filename, bufsize, dirname, relfile);
+    if (join_relfile(filename, bufsize, dirname, relfile) < 0) {
+        PyMem_RawFree(filename);
+        return NULL;
+    }
     return filename;
 }
 
@@ -2180,6 +2183,7 @@
 wchar_t *
 _Py_normpath(wchar_t *path, Py_ssize_t size)
 {
+    assert(path != NULL);
     if (!path[0] || size == 0) {
         return path;
     }
