|
|
1163ee |
diff --git a/Doc/using/cmdline.rst b/Doc/using/cmdline.rst
|
|
|
1163ee |
index d14793a..65aa3ad 100644
|
|
|
1163ee |
--- a/Doc/using/cmdline.rst
|
|
|
1163ee |
+++ b/Doc/using/cmdline.rst
|
|
|
1163ee |
@@ -728,6 +728,45 @@ conflict.
|
|
|
1163ee |
|
|
|
1163ee |
.. versionadded:: 3.6
|
|
|
1163ee |
|
|
|
1163ee |
+
|
|
|
1163ee |
+.. envvar:: PYTHONCOERCECLOCALE
|
|
|
1163ee |
+
|
|
|
1163ee |
+ If set to the value ``0``, causes the main Python command line application
|
|
|
1163ee |
+ to skip coercing the legacy ASCII-based C locale to a more capable UTF-8
|
|
|
1163ee |
+ based alternative. Note that this setting is checked even when the
|
|
|
1163ee |
+ :option:`-E` or :option:`-I` options are used, as it is handled prior to
|
|
|
1163ee |
+ the processing of command line options.
|
|
|
1163ee |
+
|
|
|
1163ee |
+ If this variable is *not* set, or is set to a value other than ``0``, and
|
|
|
1163ee |
+ the current locale reported for the ``LC_CTYPE`` category is the default
|
|
|
1163ee |
+ ``C`` locale, then the Python CLI will attempt to configure one of the
|
|
|
1163ee |
+ following locales for the given locale categories before loading the
|
|
|
1163ee |
+ interpreter runtime:
|
|
|
1163ee |
+
|
|
|
1163ee |
+ * ``C.UTF-8`` (``LC_ALL``)
|
|
|
1163ee |
+ * ``C.utf8`` (``LC_ALL``)
|
|
|
1163ee |
+ * ``UTF-8`` (``LC_CTYPE``)
|
|
|
1163ee |
+
|
|
|
1163ee |
+ If setting one of these locale categories succeeds, then the matching
|
|
|
1163ee |
+ environment variables will be set (both ``LC_ALL`` and ``LANG`` for the
|
|
|
1163ee |
+ ``LC_ALL`` category, and ``LC_CTYPE`` for the ``LC_CTYPE`` category) in
|
|
|
1163ee |
+ the current process environment before the Python runtime is initialized.
|
|
|
1163ee |
+
|
|
|
1163ee |
+ Configuring one of these locales (either explicitly or via the above
|
|
|
1163ee |
+ implicit locale coercion) will automatically set the error handler for
|
|
|
1163ee |
+ :data:`sys.stdin` and :data:`sys.stdout` to ``surrogateescape``. This
|
|
|
1163ee |
+ behavior can be overridden using :envvar:`PYTHONIOENCODING` as usual.
|
|
|
1163ee |
+
|
|
|
1163ee |
+ For debugging purposes, setting ``PYTHONCOERCECLOCALE=warn`` will cause
|
|
|
1163ee |
+ Python to emit warning messages on ``stderr`` if either the locale coercion
|
|
|
1163ee |
+ activates, or else if a locale that *would* have triggered coercion is
|
|
|
1163ee |
+ still active when the Python runtime is initialized.
|
|
|
1163ee |
+
|
|
|
1163ee |
+ Availability: \*nix
|
|
|
1163ee |
+
|
|
|
1163ee |
+ .. versionadded:: 3.7
|
|
|
1163ee |
+ See :pep:`538` for more details.
|
|
|
1163ee |
+
|
|
|
1163ee |
Debug-mode variables
|
|
|
1163ee |
~~~~~~~~~~~~~~~~~~~~
|
|
|
1163ee |
|
|
|
1163ee |
diff --git a/Lib/test/support/script_helper.py b/Lib/test/support/script_helper.py
|
|
|
1163ee |
index 507dc48..c3cb720 100644
|
|
|
1163ee |
--- a/Lib/test/support/script_helper.py
|
|
|
1163ee |
+++ b/Lib/test/support/script_helper.py
|
|
|
1163ee |
@@ -56,8 +56,35 @@ def interpreter_requires_environment():
|
|
|
1163ee |
return __cached_interp_requires_environment
|
|
|
1163ee |
|
|
|
1163ee |
|
|
|
1163ee |
-_PythonRunResult = collections.namedtuple("_PythonRunResult",
|
|
|
1163ee |
- ("rc", "out", "err"))
|
|
|
1163ee |
+class _PythonRunResult(collections.namedtuple("_PythonRunResult",
|
|
|
1163ee |
+ ("rc", "out", "err"))):
|
|
|
1163ee |
+ """Helper for reporting Python subprocess run results"""
|
|
|
1163ee |
+ def fail(self, cmd_line):
|
|
|
1163ee |
+ """Provide helpful details about failed subcommand runs"""
|
|
|
1163ee |
+ # Limit to 80 lines to ASCII characters
|
|
|
1163ee |
+ maxlen = 80 * 100
|
|
|
1163ee |
+ out, err = self.out, self.err
|
|
|
1163ee |
+ if len(out) > maxlen:
|
|
|
1163ee |
+ out = b'(... truncated stdout ...)' + out[-maxlen:]
|
|
|
1163ee |
+ if len(err) > maxlen:
|
|
|
1163ee |
+ err = b'(... truncated stderr ...)' + err[-maxlen:]
|
|
|
1163ee |
+ out = out.decode('ascii', 'replace').rstrip()
|
|
|
1163ee |
+ err = err.decode('ascii', 'replace').rstrip()
|
|
|
1163ee |
+ raise AssertionError("Process return code is %d\n"
|
|
|
1163ee |
+ "command line: %r\n"
|
|
|
1163ee |
+ "\n"
|
|
|
1163ee |
+ "stdout:\n"
|
|
|
1163ee |
+ "---\n"
|
|
|
1163ee |
+ "%s\n"
|
|
|
1163ee |
+ "---\n"
|
|
|
1163ee |
+ "\n"
|
|
|
1163ee |
+ "stderr:\n"
|
|
|
1163ee |
+ "---\n"
|
|
|
1163ee |
+ "%s\n"
|
|
|
1163ee |
+ "---"
|
|
|
1163ee |
+ % (self.rc, cmd_line,
|
|
|
1163ee |
+ out,
|
|
|
1163ee |
+ err))
|
|
|
1163ee |
|
|
|
1163ee |
|
|
|
1163ee |
# Executing the interpreter in a subprocess
|
|
|
1163ee |
@@ -115,30 +142,7 @@ def run_python_until_end(*args, **env_vars):
|
|
|
1163ee |
def _assert_python(expected_success, *args, **env_vars):
|
|
|
1163ee |
res, cmd_line = run_python_until_end(*args, **env_vars)
|
|
|
1163ee |
if (res.rc and expected_success) or (not res.rc and not expected_success):
|
|
|
1163ee |
- # Limit to 80 lines to ASCII characters
|
|
|
1163ee |
- maxlen = 80 * 100
|
|
|
1163ee |
- out, err = res.out, res.err
|
|
|
1163ee |
- if len(out) > maxlen:
|
|
|
1163ee |
- out = b'(... truncated stdout ...)' + out[-maxlen:]
|
|
|
1163ee |
- if len(err) > maxlen:
|
|
|
1163ee |
- err = b'(... truncated stderr ...)' + err[-maxlen:]
|
|
|
1163ee |
- out = out.decode('ascii', 'replace').rstrip()
|
|
|
1163ee |
- err = err.decode('ascii', 'replace').rstrip()
|
|
|
1163ee |
- raise AssertionError("Process return code is %d\n"
|
|
|
1163ee |
- "command line: %r\n"
|
|
|
1163ee |
- "\n"
|
|
|
1163ee |
- "stdout:\n"
|
|
|
1163ee |
- "---\n"
|
|
|
1163ee |
- "%s\n"
|
|
|
1163ee |
- "---\n"
|
|
|
1163ee |
- "\n"
|
|
|
1163ee |
- "stderr:\n"
|
|
|
1163ee |
- "---\n"
|
|
|
1163ee |
- "%s\n"
|
|
|
1163ee |
- "---"
|
|
|
1163ee |
- % (res.rc, cmd_line,
|
|
|
1163ee |
- out,
|
|
|
1163ee |
- err))
|
|
|
1163ee |
+ res.fail(cmd_line)
|
|
|
1163ee |
return res
|
|
|
1163ee |
|
|
|
1163ee |
def assert_python_ok(*args, **env_vars):
|
|
|
1163ee |
diff --git a/Lib/test/test_c_locale_coercion.py b/Lib/test/test_c_locale_coercion.py
|
|
|
1163ee |
new file mode 100644
|
|
|
1163ee |
index 0000000..635c98f
|
|
|
1163ee |
--- /dev/null
|
|
|
1163ee |
+++ b/Lib/test/test_c_locale_coercion.py
|
|
|
1163ee |
@@ -0,0 +1,371 @@
|
|
|
1163ee |
+# Tests the attempted automatic coercion of the C locale to a UTF-8 locale
|
|
|
1163ee |
+
|
|
|
1163ee |
+import unittest
|
|
|
1163ee |
+import locale
|
|
|
1163ee |
+import os
|
|
|
1163ee |
+import sys
|
|
|
1163ee |
+import sysconfig
|
|
|
1163ee |
+import shutil
|
|
|
1163ee |
+import subprocess
|
|
|
1163ee |
+from collections import namedtuple
|
|
|
1163ee |
+
|
|
|
1163ee |
+import test.support
|
|
|
1163ee |
+from test.support.script_helper import (
|
|
|
1163ee |
+ run_python_until_end,
|
|
|
1163ee |
+ interpreter_requires_environment,
|
|
|
1163ee |
+)
|
|
|
1163ee |
+
|
|
|
1163ee |
+# Set our expectation for the default encoding used in the C locale
|
|
|
1163ee |
+# for the filesystem encoding and the standard streams
|
|
|
1163ee |
+
|
|
|
1163ee |
+# AIX uses iso8859-1 in the C locale, other *nix platforms use ASCII
|
|
|
1163ee |
+if sys.platform.startswith("aix"):
|
|
|
1163ee |
+ C_LOCALE_STREAM_ENCODING = "iso8859-1"
|
|
|
1163ee |
+else:
|
|
|
1163ee |
+ C_LOCALE_STREAM_ENCODING = "ascii"
|
|
|
1163ee |
+
|
|
|
1163ee |
+# FS encoding is UTF-8 on macOS, other *nix platforms use the locale encoding
|
|
|
1163ee |
+if sys.platform == "darwin":
|
|
|
1163ee |
+ C_LOCALE_FS_ENCODING = "utf-8"
|
|
|
1163ee |
+else:
|
|
|
1163ee |
+ C_LOCALE_FS_ENCODING = C_LOCALE_STREAM_ENCODING
|
|
|
1163ee |
+
|
|
|
1163ee |
+# Note that the above is probably still wrong in some cases, such as:
|
|
|
1163ee |
+# * Windows when PYTHONLEGACYWINDOWSFSENCODING is set
|
|
|
1163ee |
+# * AIX and any other platforms that use latin-1 in the C locale
|
|
|
1163ee |
+#
|
|
|
1163ee |
+# Options for dealing with this:
|
|
|
1163ee |
+# * Don't set PYTHON_COERCE_C_LOCALE on such platforms (e.g. Windows doesn't)
|
|
|
1163ee |
+# * Fix the test expectations to match the actual platform behaviour
|
|
|
1163ee |
+
|
|
|
1163ee |
+# In order to get the warning messages to match up as expected, the candidate
|
|
|
1163ee |
+# order here must much the target locale order in Python/pylifecycle.c
|
|
|
1163ee |
+_C_UTF8_LOCALES = ("C.UTF-8", "C.utf8", "UTF-8")
|
|
|
1163ee |
+
|
|
|
1163ee |
+# There's no reliable cross-platform way of checking locale alias
|
|
|
1163ee |
+# lists, so the only way of knowing which of these locales will work
|
|
|
1163ee |
+# is to try them with locale.setlocale(). We do that in a subprocess
|
|
|
1163ee |
+# to avoid altering the locale of the test runner.
|
|
|
1163ee |
+#
|
|
|
1163ee |
+# If the relevant locale module attributes exist, and we're not on a platform
|
|
|
1163ee |
+# where we expect it to always succeed, we also check that
|
|
|
1163ee |
+# `locale.nl_langinfo(locale.CODESET)` works, as if it fails, the interpreter
|
|
|
1163ee |
+# will skip locale coercion for that particular target locale
|
|
|
1163ee |
+_check_nl_langinfo_CODESET = bool(
|
|
|
1163ee |
+ sys.platform not in ("darwin", "linux") and
|
|
|
1163ee |
+ hasattr(locale, "nl_langinfo") and
|
|
|
1163ee |
+ hasattr(locale, "CODESET")
|
|
|
1163ee |
+)
|
|
|
1163ee |
+
|
|
|
1163ee |
+def _set_locale_in_subprocess(locale_name):
|
|
|
1163ee |
+ cmd_fmt = "import locale; print(locale.setlocale(locale.LC_CTYPE, '{}'))"
|
|
|
1163ee |
+ if _check_nl_langinfo_CODESET:
|
|
|
1163ee |
+ # If there's no valid CODESET, we expect coercion to be skipped
|
|
|
1163ee |
+ cmd_fmt += "; import sys; sys.exit(not locale.nl_langinfo(locale.CODESET))"
|
|
|
1163ee |
+ cmd = cmd_fmt.format(locale_name)
|
|
|
1163ee |
+ result, py_cmd = run_python_until_end("-c", cmd, __isolated=True)
|
|
|
1163ee |
+ return result.rc == 0
|
|
|
1163ee |
+
|
|
|
1163ee |
+
|
|
|
1163ee |
+
|
|
|
1163ee |
+_fields = "fsencoding stdin_info stdout_info stderr_info lang lc_ctype lc_all"
|
|
|
1163ee |
+_EncodingDetails = namedtuple("EncodingDetails", _fields)
|
|
|
1163ee |
+
|
|
|
1163ee |
+class EncodingDetails(_EncodingDetails):
|
|
|
1163ee |
+ # XXX (ncoghlan): Using JSON for child state reporting may be less fragile
|
|
|
1163ee |
+ CHILD_PROCESS_SCRIPT = ";".join([
|
|
|
1163ee |
+ "import sys, os",
|
|
|
1163ee |
+ "print(sys.getfilesystemencoding())",
|
|
|
1163ee |
+ "print(sys.stdin.encoding + ':' + sys.stdin.errors)",
|
|
|
1163ee |
+ "print(sys.stdout.encoding + ':' + sys.stdout.errors)",
|
|
|
1163ee |
+ "print(sys.stderr.encoding + ':' + sys.stderr.errors)",
|
|
|
1163ee |
+ "print(os.environ.get('LANG', 'not set'))",
|
|
|
1163ee |
+ "print(os.environ.get('LC_CTYPE', 'not set'))",
|
|
|
1163ee |
+ "print(os.environ.get('LC_ALL', 'not set'))",
|
|
|
1163ee |
+ ])
|
|
|
1163ee |
+
|
|
|
1163ee |
+ @classmethod
|
|
|
1163ee |
+ def get_expected_details(cls, coercion_expected, fs_encoding, stream_encoding, env_vars):
|
|
|
1163ee |
+ """Returns expected child process details for a given encoding"""
|
|
|
1163ee |
+ _stream = stream_encoding + ":{}"
|
|
|
1163ee |
+ # stdin and stdout should use surrogateescape either because the
|
|
|
1163ee |
+ # coercion triggered, or because the C locale was detected
|
|
|
1163ee |
+ stream_info = 2*[_stream.format("surrogateescape")]
|
|
|
1163ee |
+ # stderr should always use backslashreplace
|
|
|
1163ee |
+ stream_info.append(_stream.format("backslashreplace"))
|
|
|
1163ee |
+ expected_lang = env_vars.get("LANG", "not set").lower()
|
|
|
1163ee |
+ if coercion_expected:
|
|
|
1163ee |
+ expected_lc_ctype = CLI_COERCION_TARGET.lower()
|
|
|
1163ee |
+ else:
|
|
|
1163ee |
+ expected_lc_ctype = env_vars.get("LC_CTYPE", "not set").lower()
|
|
|
1163ee |
+ expected_lc_all = env_vars.get("LC_ALL", "not set").lower()
|
|
|
1163ee |
+ env_info = expected_lang, expected_lc_ctype, expected_lc_all
|
|
|
1163ee |
+ return dict(cls(fs_encoding, *stream_info, *env_info)._asdict())
|
|
|
1163ee |
+
|
|
|
1163ee |
+ @staticmethod
|
|
|
1163ee |
+ def _handle_output_variations(data):
|
|
|
1163ee |
+ """Adjust the output to handle platform specific idiosyncrasies
|
|
|
1163ee |
+
|
|
|
1163ee |
+ * Some platforms report ASCII as ANSI_X3.4-1968
|
|
|
1163ee |
+ * Some platforms report ASCII as US-ASCII
|
|
|
1163ee |
+ * Some platforms report UTF-8 instead of utf-8
|
|
|
1163ee |
+ """
|
|
|
1163ee |
+ data = data.replace(b"ANSI_X3.4-1968", b"ascii")
|
|
|
1163ee |
+ data = data.replace(b"US-ASCII", b"ascii")
|
|
|
1163ee |
+ data = data.lower()
|
|
|
1163ee |
+ return data
|
|
|
1163ee |
+
|
|
|
1163ee |
+ @classmethod
|
|
|
1163ee |
+ def get_child_details(cls, env_vars):
|
|
|
1163ee |
+ """Retrieves fsencoding and standard stream details from a child process
|
|
|
1163ee |
+
|
|
|
1163ee |
+ Returns (encoding_details, stderr_lines):
|
|
|
1163ee |
+
|
|
|
1163ee |
+ - encoding_details: EncodingDetails for eager decoding
|
|
|
1163ee |
+ - stderr_lines: result of calling splitlines() on the stderr output
|
|
|
1163ee |
+
|
|
|
1163ee |
+ The child is run in isolated mode if the current interpreter supports
|
|
|
1163ee |
+ that.
|
|
|
1163ee |
+ """
|
|
|
1163ee |
+ result, py_cmd = run_python_until_end(
|
|
|
1163ee |
+ "-c", cls.CHILD_PROCESS_SCRIPT,
|
|
|
1163ee |
+ __isolated=True,
|
|
|
1163ee |
+ **env_vars
|
|
|
1163ee |
+ )
|
|
|
1163ee |
+ if not result.rc == 0:
|
|
|
1163ee |
+ result.fail(py_cmd)
|
|
|
1163ee |
+ # All subprocess outputs in this test case should be pure ASCII
|
|
|
1163ee |
+ adjusted_output = cls._handle_output_variations(result.out)
|
|
|
1163ee |
+ stdout_lines = adjusted_output.decode("ascii").splitlines()
|
|
|
1163ee |
+ child_encoding_details = dict(cls(*stdout_lines)._asdict())
|
|
|
1163ee |
+ stderr_lines = result.err.decode("ascii").rstrip().splitlines()
|
|
|
1163ee |
+ return child_encoding_details, stderr_lines
|
|
|
1163ee |
+
|
|
|
1163ee |
+
|
|
|
1163ee |
+# Details of the shared library warning emitted at runtime
|
|
|
1163ee |
+LEGACY_LOCALE_WARNING = (
|
|
|
1163ee |
+ "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
|
|
|
1163ee |
+ "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
|
|
|
1163ee |
+ "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
|
|
|
1163ee |
+ "locales is recommended."
|
|
|
1163ee |
+)
|
|
|
1163ee |
+
|
|
|
1163ee |
+# Details of the CLI locale coercion warning emitted at runtime
|
|
|
1163ee |
+CLI_COERCION_WARNING_FMT = (
|
|
|
1163ee |
+ "Python detected LC_CTYPE=C: LC_CTYPE coerced to {} (set another locale "
|
|
|
1163ee |
+ "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior)."
|
|
|
1163ee |
+)
|
|
|
1163ee |
+
|
|
|
1163ee |
+
|
|
|
1163ee |
+AVAILABLE_TARGETS = None
|
|
|
1163ee |
+CLI_COERCION_TARGET = None
|
|
|
1163ee |
+CLI_COERCION_WARNING = None
|
|
|
1163ee |
+
|
|
|
1163ee |
+def setUpModule():
|
|
|
1163ee |
+ global AVAILABLE_TARGETS
|
|
|
1163ee |
+ global CLI_COERCION_TARGET
|
|
|
1163ee |
+ global CLI_COERCION_WARNING
|
|
|
1163ee |
+
|
|
|
1163ee |
+ if AVAILABLE_TARGETS is not None:
|
|
|
1163ee |
+ # initialization already done
|
|
|
1163ee |
+ return
|
|
|
1163ee |
+ AVAILABLE_TARGETS = []
|
|
|
1163ee |
+
|
|
|
1163ee |
+ # Find the target locales available in the current system
|
|
|
1163ee |
+ for target_locale in _C_UTF8_LOCALES:
|
|
|
1163ee |
+ if _set_locale_in_subprocess(target_locale):
|
|
|
1163ee |
+ AVAILABLE_TARGETS.append(target_locale)
|
|
|
1163ee |
+
|
|
|
1163ee |
+ if AVAILABLE_TARGETS:
|
|
|
1163ee |
+ # Coercion is expected to use the first available target locale
|
|
|
1163ee |
+ CLI_COERCION_TARGET = AVAILABLE_TARGETS[0]
|
|
|
1163ee |
+ CLI_COERCION_WARNING = CLI_COERCION_WARNING_FMT.format(CLI_COERCION_TARGET)
|
|
|
1163ee |
+
|
|
|
1163ee |
+
|
|
|
1163ee |
+class _LocaleHandlingTestCase(unittest.TestCase):
|
|
|
1163ee |
+ # Base class to check expected locale handling behaviour
|
|
|
1163ee |
+
|
|
|
1163ee |
+ def _check_child_encoding_details(self,
|
|
|
1163ee |
+ env_vars,
|
|
|
1163ee |
+ expected_fs_encoding,
|
|
|
1163ee |
+ expected_stream_encoding,
|
|
|
1163ee |
+ expected_warnings,
|
|
|
1163ee |
+ coercion_expected):
|
|
|
1163ee |
+ """Check the C locale handling for the given process environment
|
|
|
1163ee |
+
|
|
|
1163ee |
+ Parameters:
|
|
|
1163ee |
+ expected_fs_encoding: expected sys.getfilesystemencoding() result
|
|
|
1163ee |
+ expected_stream_encoding: expected encoding for standard streams
|
|
|
1163ee |
+ expected_warning: stderr output to expect (if any)
|
|
|
1163ee |
+ """
|
|
|
1163ee |
+ result = EncodingDetails.get_child_details(env_vars)
|
|
|
1163ee |
+ encoding_details, stderr_lines = result
|
|
|
1163ee |
+ expected_details = EncodingDetails.get_expected_details(
|
|
|
1163ee |
+ coercion_expected,
|
|
|
1163ee |
+ expected_fs_encoding,
|
|
|
1163ee |
+ expected_stream_encoding,
|
|
|
1163ee |
+ env_vars
|
|
|
1163ee |
+ )
|
|
|
1163ee |
+ self.assertEqual(encoding_details, expected_details)
|
|
|
1163ee |
+ if expected_warnings is None:
|
|
|
1163ee |
+ expected_warnings = []
|
|
|
1163ee |
+ self.assertEqual(stderr_lines, expected_warnings)
|
|
|
1163ee |
+
|
|
|
1163ee |
+
|
|
|
1163ee |
+class LocaleConfigurationTests(_LocaleHandlingTestCase):
|
|
|
1163ee |
+ # Test explicit external configuration via the process environment
|
|
|
1163ee |
+
|
|
|
1163ee |
+ def setUpClass():
|
|
|
1163ee |
+ # This relies on setupModule() having been run, so it can't be
|
|
|
1163ee |
+ # handled via the @unittest.skipUnless decorator
|
|
|
1163ee |
+ if not AVAILABLE_TARGETS:
|
|
|
1163ee |
+ raise unittest.SkipTest("No C-with-UTF-8 locale available")
|
|
|
1163ee |
+
|
|
|
1163ee |
+ def test_external_target_locale_configuration(self):
|
|
|
1163ee |
+
|
|
|
1163ee |
+ # Explicitly setting a target locale should give the same behaviour as
|
|
|
1163ee |
+ # is seen when implicitly coercing to that target locale
|
|
|
1163ee |
+ self.maxDiff = None
|
|
|
1163ee |
+
|
|
|
1163ee |
+ expected_fs_encoding = "utf-8"
|
|
|
1163ee |
+ expected_stream_encoding = "utf-8"
|
|
|
1163ee |
+
|
|
|
1163ee |
+ base_var_dict = {
|
|
|
1163ee |
+ "LANG": "",
|
|
|
1163ee |
+ "LC_CTYPE": "",
|
|
|
1163ee |
+ "LC_ALL": "",
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+ for env_var in ("LANG", "LC_CTYPE"):
|
|
|
1163ee |
+ for locale_to_set in AVAILABLE_TARGETS:
|
|
|
1163ee |
+ # XXX (ncoghlan): LANG=UTF-8 doesn't appear to work as
|
|
|
1163ee |
+ # expected, so skip that combination for now
|
|
|
1163ee |
+ # See https://bugs.python.org/issue30672 for discussion
|
|
|
1163ee |
+ if env_var == "LANG" and locale_to_set == "UTF-8":
|
|
|
1163ee |
+ continue
|
|
|
1163ee |
+
|
|
|
1163ee |
+ with self.subTest(env_var=env_var,
|
|
|
1163ee |
+ configured_locale=locale_to_set):
|
|
|
1163ee |
+ var_dict = base_var_dict.copy()
|
|
|
1163ee |
+ var_dict[env_var] = locale_to_set
|
|
|
1163ee |
+ self._check_child_encoding_details(var_dict,
|
|
|
1163ee |
+ expected_fs_encoding,
|
|
|
1163ee |
+ expected_stream_encoding,
|
|
|
1163ee |
+ expected_warnings=None,
|
|
|
1163ee |
+ coercion_expected=False)
|
|
|
1163ee |
+
|
|
|
1163ee |
+
|
|
|
1163ee |
+
|
|
|
1163ee |
+@test.support.cpython_only
|
|
|
1163ee |
+@unittest.skipUnless(sysconfig.get_config_var("PY_COERCE_C_LOCALE"),
|
|
|
1163ee |
+ "C locale coercion disabled at build time")
|
|
|
1163ee |
+class LocaleCoercionTests(_LocaleHandlingTestCase):
|
|
|
1163ee |
+ # Test implicit reconfiguration of the environment during CLI startup
|
|
|
1163ee |
+
|
|
|
1163ee |
+ def _check_c_locale_coercion(self,
|
|
|
1163ee |
+ fs_encoding, stream_encoding,
|
|
|
1163ee |
+ coerce_c_locale,
|
|
|
1163ee |
+ expected_warnings=None,
|
|
|
1163ee |
+ coercion_expected=True,
|
|
|
1163ee |
+ **extra_vars):
|
|
|
1163ee |
+ """Check the C locale handling for various configurations
|
|
|
1163ee |
+
|
|
|
1163ee |
+ Parameters:
|
|
|
1163ee |
+ fs_encoding: expected sys.getfilesystemencoding() result
|
|
|
1163ee |
+ stream_encoding: expected encoding for standard streams
|
|
|
1163ee |
+ coerce_c_locale: setting to use for PYTHONCOERCECLOCALE
|
|
|
1163ee |
+ None: don't set the variable at all
|
|
|
1163ee |
+ str: the value set in the child's environment
|
|
|
1163ee |
+ expected_warnings: expected warning lines on stderr
|
|
|
1163ee |
+ extra_vars: additional environment variables to set in subprocess
|
|
|
1163ee |
+ """
|
|
|
1163ee |
+ self.maxDiff = None
|
|
|
1163ee |
+
|
|
|
1163ee |
+ if not AVAILABLE_TARGETS:
|
|
|
1163ee |
+ # Locale coercion is disabled when there aren't any target locales
|
|
|
1163ee |
+ fs_encoding = C_LOCALE_FS_ENCODING
|
|
|
1163ee |
+ stream_encoding = C_LOCALE_STREAM_ENCODING
|
|
|
1163ee |
+ coercion_expected = False
|
|
|
1163ee |
+ if expected_warnings:
|
|
|
1163ee |
+ expected_warnings = [LEGACY_LOCALE_WARNING]
|
|
|
1163ee |
+
|
|
|
1163ee |
+ base_var_dict = {
|
|
|
1163ee |
+ "LANG": "",
|
|
|
1163ee |
+ "LC_CTYPE": "",
|
|
|
1163ee |
+ "LC_ALL": "",
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+ base_var_dict.update(extra_vars)
|
|
|
1163ee |
+ for env_var in ("LANG", "LC_CTYPE"):
|
|
|
1163ee |
+ for locale_to_set in ("", "C", "POSIX", "invalid.ascii"):
|
|
|
1163ee |
+ # XXX (ncoghlan): *BSD platforms don't behave as expected in the
|
|
|
1163ee |
+ # POSIX locale, so we skip that for now
|
|
|
1163ee |
+ # See https://bugs.python.org/issue30672 for discussion
|
|
|
1163ee |
+ if locale_to_set == "POSIX":
|
|
|
1163ee |
+ continue
|
|
|
1163ee |
+ with self.subTest(env_var=env_var,
|
|
|
1163ee |
+ nominal_locale=locale_to_set,
|
|
|
1163ee |
+ PYTHONCOERCECLOCALE=coerce_c_locale):
|
|
|
1163ee |
+ var_dict = base_var_dict.copy()
|
|
|
1163ee |
+ var_dict[env_var] = locale_to_set
|
|
|
1163ee |
+ if coerce_c_locale is not None:
|
|
|
1163ee |
+ var_dict["PYTHONCOERCECLOCALE"] = coerce_c_locale
|
|
|
1163ee |
+ # Check behaviour on successful coercion
|
|
|
1163ee |
+ self._check_child_encoding_details(var_dict,
|
|
|
1163ee |
+ fs_encoding,
|
|
|
1163ee |
+ stream_encoding,
|
|
|
1163ee |
+ expected_warnings,
|
|
|
1163ee |
+ coercion_expected)
|
|
|
1163ee |
+
|
|
|
1163ee |
+ def test_test_PYTHONCOERCECLOCALE_not_set(self):
|
|
|
1163ee |
+ # This should coerce to the first available target locale by default
|
|
|
1163ee |
+ self._check_c_locale_coercion("utf-8", "utf-8", coerce_c_locale=None)
|
|
|
1163ee |
+
|
|
|
1163ee |
+ def test_PYTHONCOERCECLOCALE_not_zero(self):
|
|
|
1163ee |
+ # *Any* string other than "0" is considered "set" for our purposes
|
|
|
1163ee |
+ # and hence should result in the locale coercion being enabled
|
|
|
1163ee |
+ for setting in ("", "1", "true", "false"):
|
|
|
1163ee |
+ self._check_c_locale_coercion("utf-8", "utf-8", coerce_c_locale=setting)
|
|
|
1163ee |
+
|
|
|
1163ee |
+ def test_PYTHONCOERCECLOCALE_set_to_warn(self):
|
|
|
1163ee |
+ # PYTHONCOERCECLOCALE=warn enables runtime warnings for legacy locales
|
|
|
1163ee |
+ self._check_c_locale_coercion("utf-8", "utf-8",
|
|
|
1163ee |
+ coerce_c_locale="warn",
|
|
|
1163ee |
+ expected_warnings=[CLI_COERCION_WARNING])
|
|
|
1163ee |
+
|
|
|
1163ee |
+
|
|
|
1163ee |
+ def test_PYTHONCOERCECLOCALE_set_to_zero(self):
|
|
|
1163ee |
+ # The setting "0" should result in the locale coercion being disabled
|
|
|
1163ee |
+ self._check_c_locale_coercion(C_LOCALE_FS_ENCODING,
|
|
|
1163ee |
+ C_LOCALE_STREAM_ENCODING,
|
|
|
1163ee |
+ coerce_c_locale="0",
|
|
|
1163ee |
+ coercion_expected=False)
|
|
|
1163ee |
+ # Setting LC_ALL=C shouldn't make any difference to the behaviour
|
|
|
1163ee |
+ self._check_c_locale_coercion(C_LOCALE_FS_ENCODING,
|
|
|
1163ee |
+ C_LOCALE_STREAM_ENCODING,
|
|
|
1163ee |
+ coerce_c_locale="0",
|
|
|
1163ee |
+ LC_ALL="C",
|
|
|
1163ee |
+ coercion_expected=False)
|
|
|
1163ee |
+
|
|
|
1163ee |
+ def test_LC_ALL_set_to_C(self):
|
|
|
1163ee |
+ # Setting LC_ALL should render the locale coercion ineffective
|
|
|
1163ee |
+ self._check_c_locale_coercion(C_LOCALE_FS_ENCODING,
|
|
|
1163ee |
+ C_LOCALE_STREAM_ENCODING,
|
|
|
1163ee |
+ coerce_c_locale=None,
|
|
|
1163ee |
+ LC_ALL="C",
|
|
|
1163ee |
+ coercion_expected=False)
|
|
|
1163ee |
+ # And result in a warning about a lack of locale compatibility
|
|
|
1163ee |
+ self._check_c_locale_coercion(C_LOCALE_FS_ENCODING,
|
|
|
1163ee |
+ C_LOCALE_STREAM_ENCODING,
|
|
|
1163ee |
+ coerce_c_locale="warn",
|
|
|
1163ee |
+ LC_ALL="C",
|
|
|
1163ee |
+ expected_warnings=[LEGACY_LOCALE_WARNING],
|
|
|
1163ee |
+ coercion_expected=False)
|
|
|
1163ee |
+
|
|
|
1163ee |
+def test_main():
|
|
|
1163ee |
+ test.support.run_unittest(
|
|
|
1163ee |
+ LocaleConfigurationTests,
|
|
|
1163ee |
+ LocaleCoercionTests
|
|
|
1163ee |
+ )
|
|
|
1163ee |
+ test.support.reap_children()
|
|
|
1163ee |
+
|
|
|
1163ee |
+if __name__ == "__main__":
|
|
|
1163ee |
+ test_main()
|
|
|
1163ee |
diff --git a/Lib/test/test_cmd_line.py b/Lib/test/test_cmd_line.py
|
|
|
1163ee |
index 38156b4..5922ed9 100644
|
|
|
1163ee |
--- a/Lib/test/test_cmd_line.py
|
|
|
1163ee |
+++ b/Lib/test/test_cmd_line.py
|
|
|
1163ee |
@@ -153,6 +153,7 @@ class CmdLineTest(unittest.TestCase):
|
|
|
1163ee |
env = os.environ.copy()
|
|
|
1163ee |
# Use C locale to get ascii for the locale encoding
|
|
|
1163ee |
env['LC_ALL'] = 'C'
|
|
|
1163ee |
+ env['PYTHONCOERCECLOCALE'] = '0'
|
|
|
1163ee |
code = (
|
|
|
1163ee |
b'import locale; '
|
|
|
1163ee |
b'print(ascii("' + undecodable + b'"), '
|
|
|
1163ee |
diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py
|
|
|
1163ee |
index 7866a5c..b41239a 100644
|
|
|
1163ee |
--- a/Lib/test/test_sys.py
|
|
|
1163ee |
+++ b/Lib/test/test_sys.py
|
|
|
1163ee |
@@ -680,6 +680,7 @@ class SysModuleTest(unittest.TestCase):
|
|
|
1163ee |
# Force the POSIX locale
|
|
|
1163ee |
env = os.environ.copy()
|
|
|
1163ee |
env["LC_ALL"] = "C"
|
|
|
1163ee |
+ env["PYTHONCOERCECLOCALE"] = "0"
|
|
|
1163ee |
code = '\n'.join((
|
|
|
1163ee |
'import sys',
|
|
|
1163ee |
'def dump(name):',
|
|
|
1163ee |
diff --git a/Modules/main.c b/Modules/main.c
|
|
|
1163ee |
index 585d696..96d8be4 100644
|
|
|
1163ee |
--- a/Modules/main.c
|
|
|
1163ee |
+++ b/Modules/main.c
|
|
|
1163ee |
@@ -107,7 +107,11 @@ static const char usage_6[] =
|
|
|
1163ee |
" predictable seed.\n"
|
|
|
1163ee |
"PYTHONMALLOC: set the Python memory allocators and/or install debug hooks\n"
|
|
|
1163ee |
" on Python memory allocators. Use PYTHONMALLOC=debug to install debug\n"
|
|
|
1163ee |
-" hooks.\n";
|
|
|
1163ee |
+" hooks.\n"
|
|
|
1163ee |
+
|
|
|
1163ee |
+"PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale\n"
|
|
|
1163ee |
+" coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of\n"
|
|
|
1163ee |
+" locale coercion and locale compatibility warnings on stderr.\n";
|
|
|
1163ee |
|
|
|
1163ee |
static int
|
|
|
1163ee |
usage(int exitcode, const wchar_t* program)
|
|
|
1163ee |
diff --git a/Programs/_testembed.c b/Programs/_testembed.c
|
|
|
1163ee |
index 813cf30..2a64092 100644
|
|
|
1163ee |
--- a/Programs/_testembed.c
|
|
|
1163ee |
+++ b/Programs/_testembed.c
|
|
|
1163ee |
@@ -1,4 +1,5 @@
|
|
|
1163ee |
#include <Python.h>
|
|
|
1163ee |
+#include "pyconfig.h"
|
|
|
1163ee |
#include "pythread.h"
|
|
|
1163ee |
#include <stdio.h>
|
|
|
1163ee |
|
|
|
1163ee |
diff --git a/Programs/python.c b/Programs/python.c
|
|
|
1163ee |
index a7afbc7..03f8295 100644
|
|
|
1163ee |
--- a/Programs/python.c
|
|
|
1163ee |
+++ b/Programs/python.c
|
|
|
1163ee |
@@ -15,6 +15,21 @@ wmain(int argc, wchar_t **argv)
|
|
|
1163ee |
}
|
|
|
1163ee |
#else
|
|
|
1163ee |
|
|
|
1163ee |
+/* Access private pylifecycle helper API to better handle the legacy C locale
|
|
|
1163ee |
+ *
|
|
|
1163ee |
+ * The legacy C locale assumes ASCII as the default text encoding, which
|
|
|
1163ee |
+ * causes problems not only for the CPython runtime, but also other
|
|
|
1163ee |
+ * components like GNU readline.
|
|
|
1163ee |
+ *
|
|
|
1163ee |
+ * Accordingly, when the CLI detects it, it attempts to coerce it to a
|
|
|
1163ee |
+ * more capable UTF-8 based alternative.
|
|
|
1163ee |
+ *
|
|
|
1163ee |
+ * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
|
|
|
1163ee |
+ *
|
|
|
1163ee |
+ */
|
|
|
1163ee |
+extern int _Py_LegacyLocaleDetected(void);
|
|
|
1163ee |
+extern void _Py_CoerceLegacyLocale(void);
|
|
|
1163ee |
+
|
|
|
1163ee |
int
|
|
|
1163ee |
main(int argc, char **argv)
|
|
|
1163ee |
{
|
|
|
1163ee |
@@ -25,7 +40,11 @@ main(int argc, char **argv)
|
|
|
1163ee |
char *oldloc;
|
|
|
1163ee |
|
|
|
1163ee |
/* Force malloc() allocator to bootstrap Python */
|
|
|
1163ee |
+#ifdef Py_DEBUG
|
|
|
1163ee |
+ (void)_PyMem_SetupAllocators("malloc_debug");
|
|
|
1163ee |
+# else
|
|
|
1163ee |
(void)_PyMem_SetupAllocators("malloc");
|
|
|
1163ee |
+# endif
|
|
|
1163ee |
|
|
|
1163ee |
argv_copy = (wchar_t **)PyMem_RawMalloc(sizeof(wchar_t*) * (argc+1));
|
|
|
1163ee |
argv_copy2 = (wchar_t **)PyMem_RawMalloc(sizeof(wchar_t*) * (argc+1));
|
|
|
1163ee |
@@ -49,7 +68,21 @@ main(int argc, char **argv)
|
|
|
1163ee |
return 1;
|
|
|
1163ee |
}
|
|
|
1163ee |
|
|
|
1163ee |
+#ifdef __ANDROID__
|
|
|
1163ee |
+ /* Passing "" to setlocale() on Android requests the C locale rather
|
|
|
1163ee |
+ * than checking environment variables, so request C.UTF-8 explicitly
|
|
|
1163ee |
+ */
|
|
|
1163ee |
+ setlocale(LC_ALL, "C.UTF-8");
|
|
|
1163ee |
+#else
|
|
|
1163ee |
+ /* Reconfigure the locale to the default for this process */
|
|
|
1163ee |
setlocale(LC_ALL, "");
|
|
|
1163ee |
+#endif
|
|
|
1163ee |
+
|
|
|
1163ee |
+ if (_Py_LegacyLocaleDetected()) {
|
|
|
1163ee |
+ _Py_CoerceLegacyLocale();
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+
|
|
|
1163ee |
+ /* Convert from char to wchar_t based on the locale settings */
|
|
|
1163ee |
for (i = 0; i < argc; i++) {
|
|
|
1163ee |
argv_copy[i] = Py_DecodeLocale(argv[i], NULL);
|
|
|
1163ee |
if (!argv_copy[i]) {
|
|
|
1163ee |
@@ -70,7 +103,11 @@ main(int argc, char **argv)
|
|
|
1163ee |
|
|
|
1163ee |
/* Force again malloc() allocator to release memory blocks allocated
|
|
|
1163ee |
before Py_Main() */
|
|
|
1163ee |
+#ifdef Py_DEBUG
|
|
|
1163ee |
+ (void)_PyMem_SetupAllocators("malloc_debug");
|
|
|
1163ee |
+# else
|
|
|
1163ee |
(void)_PyMem_SetupAllocators("malloc");
|
|
|
1163ee |
+# endif
|
|
|
1163ee |
|
|
|
1163ee |
for (i = 0; i < argc; i++) {
|
|
|
1163ee |
PyMem_RawFree(argv_copy2[i]);
|
|
|
1163ee |
diff --git a/Python/pylifecycle.c b/Python/pylifecycle.c
|
|
|
1163ee |
index ecfdfee..4fee178 100644
|
|
|
1163ee |
--- a/Python/pylifecycle.c
|
|
|
1163ee |
+++ b/Python/pylifecycle.c
|
|
|
1163ee |
@@ -167,6 +167,7 @@ Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
|
|
|
1163ee |
return 0;
|
|
|
1163ee |
}
|
|
|
1163ee |
|
|
|
1163ee |
+
|
|
|
1163ee |
/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
|
|
|
1163ee |
call this twice without an intervening Py_FinalizeEx() call. When
|
|
|
1163ee |
initializations fail, a fatal error is issued and the function does
|
|
|
1163ee |
@@ -301,6 +302,183 @@ import_init(PyInterpreterState *interp, PyObject *sysmod)
|
|
|
1163ee |
}
|
|
|
1163ee |
|
|
|
1163ee |
|
|
|
1163ee |
+/* Helper functions to better handle the legacy C locale
|
|
|
1163ee |
+ *
|
|
|
1163ee |
+ * The legacy C locale assumes ASCII as the default text encoding, which
|
|
|
1163ee |
+ * causes problems not only for the CPython runtime, but also other
|
|
|
1163ee |
+ * components like GNU readline.
|
|
|
1163ee |
+ *
|
|
|
1163ee |
+ * Accordingly, when the CLI detects it, it attempts to coerce it to a
|
|
|
1163ee |
+ * more capable UTF-8 based alternative as follows:
|
|
|
1163ee |
+ *
|
|
|
1163ee |
+ * if (_Py_LegacyLocaleDetected()) {
|
|
|
1163ee |
+ * _Py_CoerceLegacyLocale();
|
|
|
1163ee |
+ * }
|
|
|
1163ee |
+ *
|
|
|
1163ee |
+ * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
|
|
|
1163ee |
+ *
|
|
|
1163ee |
+ * Locale coercion also impacts the default error handler for the standard
|
|
|
1163ee |
+ * streams: while the usual default is "strict", the default for the legacy
|
|
|
1163ee |
+ * C locale and for any of the coercion target locales is "surrogateescape".
|
|
|
1163ee |
+ */
|
|
|
1163ee |
+
|
|
|
1163ee |
+int
|
|
|
1163ee |
+_Py_LegacyLocaleDetected(void)
|
|
|
1163ee |
+{
|
|
|
1163ee |
+#ifndef MS_WINDOWS
|
|
|
1163ee |
+ /* On non-Windows systems, the C locale is considered a legacy locale */
|
|
|
1163ee |
+ /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
|
|
|
1163ee |
+ * the POSIX locale as a simple alias for the C locale, so
|
|
|
1163ee |
+ * we may also want to check for that explicitly.
|
|
|
1163ee |
+ */
|
|
|
1163ee |
+ const char *ctype_loc = setlocale(LC_CTYPE, NULL);
|
|
|
1163ee |
+ return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
|
|
|
1163ee |
+#else
|
|
|
1163ee |
+ /* Windows uses code pages instead of locales, so no locale is legacy */
|
|
|
1163ee |
+ return 0;
|
|
|
1163ee |
+#endif
|
|
|
1163ee |
+}
|
|
|
1163ee |
+
|
|
|
1163ee |
+
|
|
|
1163ee |
+static const char *_C_LOCALE_WARNING =
|
|
|
1163ee |
+ "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
|
|
|
1163ee |
+ "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
|
|
|
1163ee |
+ "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
|
|
|
1163ee |
+ "locales is recommended.\n";
|
|
|
1163ee |
+
|
|
|
1163ee |
+static int
|
|
|
1163ee |
+_legacy_locale_warnings_enabled(void)
|
|
|
1163ee |
+{
|
|
|
1163ee |
+ const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
|
|
|
1163ee |
+ return (coerce_c_locale != NULL &&
|
|
|
1163ee |
+ strncmp(coerce_c_locale, "warn", 5) == 0);
|
|
|
1163ee |
+}
|
|
|
1163ee |
+
|
|
|
1163ee |
+static void
|
|
|
1163ee |
+_emit_stderr_warning_for_legacy_locale(void)
|
|
|
1163ee |
+{
|
|
|
1163ee |
+ if (_legacy_locale_warnings_enabled()) {
|
|
|
1163ee |
+ if (_Py_LegacyLocaleDetected()) {
|
|
|
1163ee |
+ fprintf(stderr, "%s", _C_LOCALE_WARNING);
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+}
|
|
|
1163ee |
+
|
|
|
1163ee |
+typedef struct _CandidateLocale {
|
|
|
1163ee |
+ const char *locale_name; /* The locale to try as a coercion target */
|
|
|
1163ee |
+} _LocaleCoercionTarget;
|
|
|
1163ee |
+
|
|
|
1163ee |
+static _LocaleCoercionTarget _TARGET_LOCALES[] = {
|
|
|
1163ee |
+ {"C.UTF-8"},
|
|
|
1163ee |
+ {"C.utf8"},
|
|
|
1163ee |
+ {"UTF-8"},
|
|
|
1163ee |
+ {NULL}
|
|
|
1163ee |
+};
|
|
|
1163ee |
+
|
|
|
1163ee |
+static char *
|
|
|
1163ee |
+get_default_standard_stream_error_handler(void)
|
|
|
1163ee |
+{
|
|
|
1163ee |
+ const char *ctype_loc = setlocale(LC_CTYPE, NULL);
|
|
|
1163ee |
+ if (ctype_loc != NULL) {
|
|
|
1163ee |
+ /* "surrogateescape" is the default in the legacy C locale */
|
|
|
1163ee |
+ if (strcmp(ctype_loc, "C") == 0) {
|
|
|
1163ee |
+ return "surrogateescape";
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+
|
|
|
1163ee |
+#ifdef PY_COERCE_C_LOCALE
|
|
|
1163ee |
+ /* "surrogateescape" is the default in locale coercion target locales */
|
|
|
1163ee |
+ const _LocaleCoercionTarget *target = NULL;
|
|
|
1163ee |
+ for (target = _TARGET_LOCALES; target->locale_name; target++) {
|
|
|
1163ee |
+ if (strcmp(ctype_loc, target->locale_name) == 0) {
|
|
|
1163ee |
+ return "surrogateescape";
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+#endif
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+
|
|
|
1163ee |
+ /* Otherwise return NULL to request the typical default error handler */
|
|
|
1163ee |
+ return NULL;
|
|
|
1163ee |
+}
|
|
|
1163ee |
+
|
|
|
1163ee |
+#ifdef PY_COERCE_C_LOCALE
|
|
|
1163ee |
+static const char *_C_LOCALE_COERCION_WARNING =
|
|
|
1163ee |
+ "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
|
|
|
1163ee |
+ "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
|
|
|
1163ee |
+
|
|
|
1163ee |
+static void
|
|
|
1163ee |
+_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
|
|
|
1163ee |
+{
|
|
|
1163ee |
+
|
|
|
1163ee |
+ const char *newloc = target->locale_name;
|
|
|
1163ee |
+
|
|
|
1163ee |
+ /* Reset locale back to currently configured defaults */
|
|
|
1163ee |
+ setlocale(LC_ALL, "");
|
|
|
1163ee |
+
|
|
|
1163ee |
+ /* Set the relevant locale environment variable */
|
|
|
1163ee |
+ if (setenv("LC_CTYPE", newloc, 1)) {
|
|
|
1163ee |
+ fprintf(stderr,
|
|
|
1163ee |
+ "Error setting LC_CTYPE, skipping C locale coercion\n");
|
|
|
1163ee |
+ return;
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+ if (_legacy_locale_warnings_enabled()) {
|
|
|
1163ee |
+ fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+
|
|
|
1163ee |
+ /* Reconfigure with the overridden environment variables */
|
|
|
1163ee |
+ setlocale(LC_ALL, "");
|
|
|
1163ee |
+}
|
|
|
1163ee |
+#endif
|
|
|
1163ee |
+
|
|
|
1163ee |
+
|
|
|
1163ee |
+void
|
|
|
1163ee |
+_Py_CoerceLegacyLocale(void)
|
|
|
1163ee |
+{
|
|
|
1163ee |
+#ifdef PY_COERCE_C_LOCALE
|
|
|
1163ee |
+ /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
|
|
|
1163ee |
+ * the locale settings *before* we try to do anything with the command
|
|
|
1163ee |
+ * line arguments. For cross-platform debugging purposes, we also need
|
|
|
1163ee |
+ * to give end users a way to force even scripts that are otherwise
|
|
|
1163ee |
+ * isolated from their environment to use the legacy ASCII-centric C
|
|
|
1163ee |
+ * locale.
|
|
|
1163ee |
+ *
|
|
|
1163ee |
+ * Ignoring -E and -I is safe from a security perspective, as we only use
|
|
|
1163ee |
+ * the setting to turn *off* the implicit locale coercion, and anyone with
|
|
|
1163ee |
+ * access to the process environment already has the ability to set
|
|
|
1163ee |
+ * `LC_ALL=C` to override the C level locale settings anyway.
|
|
|
1163ee |
+ */
|
|
|
1163ee |
+ const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
|
|
|
1163ee |
+ if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
|
|
|
1163ee |
+ /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
|
|
|
1163ee |
+ const char *locale_override = getenv("LC_ALL");
|
|
|
1163ee |
+ if (locale_override == NULL || *locale_override == '\0') {
|
|
|
1163ee |
+ /* LC_ALL is also not set (or is set to an empty string) */
|
|
|
1163ee |
+ const _LocaleCoercionTarget *target = NULL;
|
|
|
1163ee |
+ for (target = _TARGET_LOCALES; target->locale_name; target++) {
|
|
|
1163ee |
+ const char *new_locale = setlocale(LC_CTYPE,
|
|
|
1163ee |
+ target->locale_name);
|
|
|
1163ee |
+ if (new_locale != NULL) {
|
|
|
1163ee |
+#if !defined(__APPLE__) && defined(HAVE_LANGINFO_H) && defined(CODESET)
|
|
|
1163ee |
+ /* Also ensure that nl_langinfo works in this locale */
|
|
|
1163ee |
+ char *codeset = nl_langinfo(CODESET);
|
|
|
1163ee |
+ if (!codeset || *codeset == '\0') {
|
|
|
1163ee |
+ /* CODESET is not set or empty, so skip coercion */
|
|
|
1163ee |
+ new_locale = NULL;
|
|
|
1163ee |
+ setlocale(LC_CTYPE, "");
|
|
|
1163ee |
+ continue;
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+#endif
|
|
|
1163ee |
+ /* Successfully configured locale, so make it the default */
|
|
|
1163ee |
+ _coerce_default_locale_settings(target);
|
|
|
1163ee |
+ return;
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+ }
|
|
|
1163ee |
+ /* No C locale warning here, as Py_Initialize will emit one later */
|
|
|
1163ee |
+#endif
|
|
|
1163ee |
+}
|
|
|
1163ee |
+
|
|
|
1163ee |
+
|
|
|
1163ee |
void
|
|
|
1163ee |
_Py_InitializeEx_Private(int install_sigs, int install_importlib)
|
|
|
1163ee |
{
|
|
|
1163ee |
@@ -315,11 +493,19 @@ _Py_InitializeEx_Private(int install_sigs, int install_importlib)
|
|
|
1163ee |
initialized = 1;
|
|
|
1163ee |
_Py_Finalizing = NULL;
|
|
|
1163ee |
|
|
|
1163ee |
-#ifdef HAVE_SETLOCALE
|
|
|
1163ee |
+#ifdef __ANDROID__
|
|
|
1163ee |
+ /* Passing "" to setlocale() on Android requests the C locale rather
|
|
|
1163ee |
+ * than checking environment variables, so request C.UTF-8 explicitly
|
|
|
1163ee |
+ */
|
|
|
1163ee |
+ setlocale(LC_CTYPE, "C.UTF-8");
|
|
|
1163ee |
+#else
|
|
|
1163ee |
+#ifndef MS_WINDOWS
|
|
|
1163ee |
/* Set up the LC_CTYPE locale, so we can obtain
|
|
|
1163ee |
the locale's charset without having to switch
|
|
|
1163ee |
locales. */
|
|
|
1163ee |
setlocale(LC_CTYPE, "");
|
|
|
1163ee |
+ _emit_stderr_warning_for_legacy_locale();
|
|
|
1163ee |
+#endif
|
|
|
1163ee |
#endif
|
|
|
1163ee |
|
|
|
1163ee |
if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
|
|
|
1163ee |
@@ -1247,12 +1433,8 @@ initstdio(void)
|
|
|
1163ee |
}
|
|
|
1163ee |
}
|
|
|
1163ee |
if (!errors && !(pythonioencoding && *pythonioencoding)) {
|
|
|
1163ee |
- /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
|
|
|
1163ee |
- stdin and stdout use the surrogateescape error handler by
|
|
|
1163ee |
- default, instead of the strict error handler. */
|
|
|
1163ee |
- char *loc = setlocale(LC_CTYPE, NULL);
|
|
|
1163ee |
- if (loc != NULL && strcmp(loc, "C") == 0)
|
|
|
1163ee |
- errors = "surrogateescape";
|
|
|
1163ee |
+ /* Choose the default error handler based on the current locale */
|
|
|
1163ee |
+ errors = get_default_standard_stream_error_handler();
|
|
|
1163ee |
}
|
|
|
1163ee |
}
|
|
|
1163ee |
|
|
|
1163ee |
diff --git a/configure.ac b/configure.ac
|
|
|
1163ee |
index 3f2459a..7444486 100644
|
|
|
1163ee |
--- a/configure.ac
|
|
|
1163ee |
+++ b/configure.ac
|
|
|
1163ee |
@@ -3360,6 +3360,40 @@ then
|
|
|
1163ee |
fi
|
|
|
1163ee |
AC_MSG_RESULT($with_pymalloc)
|
|
|
1163ee |
|
|
|
1163ee |
+# Check for --with-c-locale-coercion
|
|
|
1163ee |
+AC_MSG_CHECKING(for --with-c-locale-coercion)
|
|
|
1163ee |
+AC_ARG_WITH(c-locale-coercion,
|
|
|
1163ee |
+ AS_HELP_STRING([--with(out)-c-locale-coercion],
|
|
|
1163ee |
+ [disable/enable C locale coercion to a UTF-8 based locale]))
|
|
|
1163ee |
+
|
|
|
1163ee |
+if test -z "$with_c_locale_coercion"
|
|
|
1163ee |
+then
|
|
|
1163ee |
+ with_c_locale_coercion="yes"
|
|
|
1163ee |
+fi
|
|
|
1163ee |
+if test "$with_c_locale_coercion" != "no"
|
|
|
1163ee |
+then
|
|
|
1163ee |
+ AC_DEFINE(PY_COERCE_C_LOCALE, 1,
|
|
|
1163ee |
+ [Define if you want to coerce the C locale to a UTF-8 based locale])
|
|
|
1163ee |
+fi
|
|
|
1163ee |
+AC_MSG_RESULT($with_c_locale_coercion)
|
|
|
1163ee |
+
|
|
|
1163ee |
+# Check for --with-c-locale-warning
|
|
|
1163ee |
+AC_MSG_CHECKING(for --with-c-locale-warning)
|
|
|
1163ee |
+AC_ARG_WITH(c-locale-warning,
|
|
|
1163ee |
+ AS_HELP_STRING([--with(out)-c-locale-warning],
|
|
|
1163ee |
+ [disable/enable locale compatibility warning in the C locale]))
|
|
|
1163ee |
+
|
|
|
1163ee |
+if test -z "$with_c_locale_warning"
|
|
|
1163ee |
+then
|
|
|
1163ee |
+ with_c_locale_warning="yes"
|
|
|
1163ee |
+fi
|
|
|
1163ee |
+if test "$with_c_locale_warning" != "no"
|
|
|
1163ee |
+then
|
|
|
1163ee |
+ AC_DEFINE(PY_WARN_ON_C_LOCALE, 1,
|
|
|
1163ee |
+ [Define to emit a locale compatibility warning in the C locale])
|
|
|
1163ee |
+fi
|
|
|
1163ee |
+AC_MSG_RESULT($with_c_locale_warning)
|
|
|
1163ee |
+
|
|
|
1163ee |
# Check for Valgrind support
|
|
|
1163ee |
AC_MSG_CHECKING([for --with-valgrind])
|
|
|
1163ee |
AC_ARG_WITH([valgrind],
|