gh-156122: Allow lone surrogates in module filenames for crossinterp - #156221
gh-156122: Allow lone surrogates in module filenames for crossinterp#156221AdityaM06 wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3721552b8e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } | ||
| else { | ||
| (void)strcpy(buffer, filename); | ||
| PyObject *bytes = PyUnicode_EncodeFSDefault(filenameobj); |
There was a problem hiding this comment.
Preserve a decodable path for re-executing main
On POSIX, a real filename containing an undecodable byte is exposed as (for example) \udcff; PyUnicode_EncodeFSDefault() converts that surrogate back to raw 0xff, not UTF-8. When a __main__ function that uses globals is unpickled in the target interpreter, runpy_run_path() later passes this buffer through Py_BuildValue("sOs") (Python/crossinterp.c:44), which strictly decodes it as UTF-8 and raises UnicodeDecodeError. Thus cross-interpreter calls from scripts with surrogate-escaped filenames still fail when they need the existing re-execution path; retain a Unicode/UTF-8-surrogatepass representation through that handoff (or pass a Unicode filename object) instead of filesystem bytes.
Useful? React with 👍 / 👎.
The Problem
When cross-interpreter calls pickle arguments via
_PyPickle_GetXIData(),_set_pickle_xid_context()invokes_Py_GetMainfile()->_PyModule_GetFilenameUTF8()to record__main__.__file__in case the module needs to be re-executed upon unpickling._PyModule_GetFilenameUTF8()previously usedPyUnicode_AsUTF8AndSize(), which strictly rejects surrogate code points. If__main__.__file__contained a lone surrogate (e.g. from an undecodable filesystem path like\udcffor\ud800),PyUnicode_AsUTF8AndSize()failed withUnicodeEncodeErrorand leftsize = -1, resulting in an assertion failure (assert(size >= 0)) in debug builds or undefined behavior in release builds.The Solution
_PyModule_GetFilenameUTF8()inObjects/moduleobject.cto encode filenames usingPyUnicode_EncodeFSDefault()instead ofPyUnicode_AsUTF8AndSize(), matching standard filesystem encoding handling withsurrogateescape.sizeremains-1and the caller_set_pickle_xid_context()safely clears the exception withPyErr_Clear().Adding Tests & Verification
test_surrogate_filename_in___main__inLib/test/test_interpreters/test_api.pycovering both:\udcff(low surrogate / PEP 383surrogateescaperange).\ud800(high surrogate / unencodable error-handling path)../python.exe -m test -v -R 3:3 test_interpreters -m test_surrogate_filename_in___main__-> 0 leaks).Misc/NEWS.d/next/Core_and_Builtins/.