Skip to content

PlatformIO STM32 Build Fails on Windows Chinese Version: TMP File Encoding Issue #4746

Description

@yehjf

Describe the bug
When I use PlatformIO to compile an STM32 program, I encounter a linking failure error. After debugging, I found that when the command becomes too long, the command arguments are written into a temporary file using the TempFileMunge method. However, since I'm using the Chinese version of Windows, the default encoding is cp936. If the temporary file is written using UTF-8 encoding, it causes errors when gcc tries to read it.
On the other hand, if the temporary file is written using GBK encoding, everything works fine.

os.write(fd, bytearray(join_char.join(args) + "\n", 'gbk'))

Therefore, the correct encoding should be selected based on the system's default locale when writing the temporary file.

Required information

  • Link to SCons Users thread discussing your issue.
  • Version of SCons
    scons-local-4.8.1
  • Version of Python
    Python 3.11.7 (tags/v3.11.7:fa7a6f2, Dec 4 2023, 19:24:49) [MSC v.1937 64 bit (AMD64)] on win32
  • Which python distribution if applicable (python.org, cygwin, anaconda, macports, brew,etc)
  • How you installed SCons
  • What Platform are you on? (Linux/Windows and which version)
    Windows 10 Pro 22H2 19045.6093 (Chinese Version)
  • How to reproduce your issue? Please include a small self contained reproducer. Likely a SConstruct should do for most issues.
  • How you invoke scons (The command line you're using "scons --flags some_arguments")

Activity

  1. bdbaddog commented on Jul 15, 2025

    @bdbaddog
    Contributor

    You should file your issue with PlatformIO!
    Also 4.8.1 is not the newest version of SCons.
    Please try with 4.9.1

    If 4.9.1 doesn't fix it, let us know and we'll take a look.

  2. yehjf commented on Jul 16, 2025

    @yehjf
    Author

    I've tried it already. PlatformIO uses the package [email protected], which references [email protected], so I can't simply upgrade it separately.
    However, I looked at the relevant code in version 4.9.1, and the temporary file is still written using UTF-8 encoding. Therefore, I suspect that compatibility issues still exist.

    SCons/Platform/init.py:282

    os.write(fd, bytearray(join_char.join(args) + "\n", encoding="utf-8"))
    
  3. bdbaddog commented on Jul 16, 2025

    @bdbaddog
    Contributor

    @yehjf what does the following python code output on your system

    import sys
    print(sys.getdefaultencoding())
    
  4. yehjf commented on Jul 16, 2025

    @yehjf
    Author

    Display utf-8

    After my debugging, I found that after writing the temporary file (which contains Chinese characters), the command is eventually executed via the spawnve method:󠁪

    C:\WINDOWS\System32\cmd.exe /C arm-none-eabi-g++ @D:\\Desktop\\测试\\firmware\\.pio\\build\\bluepill_f103c6\\tmpagpc__cg.tmp
    

    The key issue is that the g++ program reads this temporary file using GBK encoding. I suspect that g++ uses the default encoding from the Windows locale settings when opening the tmp file.

    I tried running the command chcp 65001 before execution to switch to UTF-8 mode, but it still didn't work.
    However, when I changed the encoding to GBK when writing the tmp file, the command was executed successfully.

    By default, the result of chcp on my system is 936, which corresponds to GBK encoding.

  5. mwichmann commented on Jul 16, 2025

    @mwichmann
    Collaborator

    Yeah, these days Python itself defaults to utf-8 (for the most part), and we're forcing it in that case, that's not necessarily the case for an external command.

  6. bdbaddog commented on Jul 16, 2025

    @bdbaddog
    Contributor
  7. yehjf commented on Jul 17, 2025

    @yehjf
    Author
    ALLUSERSPROFILE=C:\ProgramData
    ANDROID_SDK_ROOT=D:\android-sdk
    APPDATA=C:\Users\Hello\AppData\Roaming
    CommonProgramFiles=C:\Program Files\Common Files
    CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
    CommonProgramW6432=C:\Program Files\Common Files
    COMPUTERNAME=DESKTOP-P357RS7
    ComSpec=C:\WINDOWS\system32\cmd.exe
    DriverData=C:\Windows\System32\Drivers\DriverData
    GHIDRA_INSTALL_DIR=D:\scoop\apps\ghidra\current
    GIT_INSTALL_ROOT=D:\scoop\apps\git\current
    GRADLE_USER_HOME=D:\scoop\apps\gradle\current\.gradle
    HADOOP_HOME=D:\hadoop-3.3.5
    HOMEDRIVE=C:
    HOMEPATH=\Users\Hello
    JAVA_HOME=C:\Program Files\Java\jdk1.8.0_181
    LOCALAPPDATA=C:\Users\Hello\AppData\Local
    LOGONSERVER=\\DESKTOP-P357RS7
    NUMBER_OF_PROCESSORS=6
    OneDrive=C:\Users\Hello\OneDrive
    OneDriveConsumer=C:\Users\Hello\OneDrive
    OS=Windows_NT
    Path=D:\scoop\apps\shims;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Java\jdk1.8.0_181\bin;C:\Program Files (x86)\Windows Kits\10\Debuggers\x64;C:\Program Files (x86)\ZeroTier\One\;C:\Program Files\dotnet\;E:\metasploit-framework\bin\;C:\Program Files\Docker\Docker\resources\bin;D:\hadoop-3.3.5\bin;D:\scoop\apps\python36\current\Scripts;D:\scoop\apps\python36\current;D:\scoop\apps\nodejs\current\bin;D:\scoop\apps\nodejs\current;D:\scoop\apps\vscode\current\bin;D:\scoop\apps\python39\current\Scripts;D:\scoop\apps\python39\current;D:\scoop\apps\openjdk\current\bin;D:\scoop\apps\python310\current\Scripts;D:\scoop\apps\python310\current;D:\scoop\apps\python\current\Scripts;D:\scoop\apps\python\current;C:\Users\Hello\go\bin;D:\scoop\shims;C:\Users\Hello\AppData\Local\Microsoft\WindowsApps;C:\Users\Hello\.dotnet\tools
    PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
    PROCESSOR_ARCHITECTURE=AMD64
    PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 158 Stepping 13, GenuineIntel
    PROCESSOR_LEVEL=6
    PROCESSOR_REVISION=9e0d
    ProgramData=C:\ProgramData
    ProgramFiles=C:\Program Files
    ProgramFiles(x86)=C:\Program Files (x86)
    ProgramW6432=C:\Program Files
    PROMPT=$P$G
    PSModulePath=C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
    PUBLIC=C:\Users\Public
    PYSPARK_DRIVER_PYTHON=D:\scoop\apps\python\current\python.exe
    PYSPARK_PYTHON=D:\scoop\apps\python\current\python.exe
    SBT_HOME=D:\scoop\apps\sbt\current
    SCALA_HOME=D:\scoop\apps\scala2\current
    SESSIONNAME=Console
    SystemDrive=C:
    SystemRoot=C:\WINDOWS
    TEMP=C:\Users\Hello\AppData\Local\Temp
    TMP=C:\Users\Hello\AppData\Local\Temp
    USERDOMAIN=DESKTOP-P357RS7
    USERDOMAIN_ROAMINGPROFILE=DESKTOP-P357RS7
    USERNAME=Hello
    USERPROFILE=C:\Users\Hello
    windir=C:\WINDOWS
    WIRESHARK_CONFIG_DIR=D:\scoop\apps\wireshark\current\Data
    WIRESHARK_DATA_DIR=D:\scoop\apps\wireshark\current\Data
    ZES_ENABLE_SYSMAN=1
    
  8. bdbaddog commented on Jul 17, 2025

    @bdbaddog
    Contributor

    How about try this:

    import locale
    
    default_encoding = locale.getpreferredencoding(False)
    print(f"The Windows default encoding for Python is: {default_encoding}")
    
  9. yehjf commented on Jul 17, 2025

    @yehjf
    Author
    The Windows default encoding for Python is: cp936
    
  10. added
    TEMPFILE
    on Jul 19, 2025
  11. added theissue type on Jul 19, 2025
  12. mwichmann commented on Jul 19, 2025

    @mwichmann
    Collaborator

    To some of the above: sys.getdefaultencoding() is not useful, it's defined to return utf-8 these days. That's for Python. locale.getencoding() is far more interesting.

    sys.getdefaultencoding()
    Return 'utf-8'. This is the name of the default string encoding, used in methods like str.encode.

    I wonder if the answer is to just omit the encoding, letting it default? Hard to test for me, I only have English Windows, and on Linux it's hard to force things into non-UTF-8.

  13. jcbrill commented on Jul 20, 2025

    @jcbrill
    Contributor

    I only have English Windows

    With a VMWare or VirtualBox Windows VM, it would be possible to change the Windows language/locale for testing.

    I did that for some testing a while back using German. I think the language and keyboard was changed I don't remember exactly. Not knowing the language made using the keyboard a challenge to launch the tests though.

  14. mwichmann commented on Jul 20, 2025

    @mwichmann
    Collaborator

    I've done that too, but it needs to be a different enough locale to trigger the problem.

  15. 59 remaining items

  16. jcbrill commented on Jul 27, 2025

    @jcbrill
    Contributor

    My current feeling is this is just too complex to solve, and we should leave it to the user to deal with (set an alternate codec if you need it).

    Yes. Automatically changing the encoding from utf-8 is just asking for trouble.

    This seems to be a Python shortcoming: for this one very narrow test (one specific code point), Microsoft did eventually add the euro symbol to cp936, but the Python codec implementation does not (according to the Internet)

    That particular encoding error was unexpected.

    Windows paths are effectively utf-16 which is a large candidate set of characters and target encodings may accept a significantly smaller set of characters. Converting to utf-8 is largely going to be successful.

    Single byte encodings like cp1252 and cp437 are going to have UnicodeErrors for a large set of extended characters. The set of unsupported extended characters will differ by encoding.

    Similarly for double byte encodings like cp936, there may exist characters allowed in windows paths with multi-byte encodings that may not be convertible.

    As soon as a user is able to change the encoding, unicode encoding errors become more likely.

  17. jcbrill commented on Jul 28, 2025

    @jcbrill
    Contributor

    @mwichmann Interesting code at bottom of py 3.13.2 encodings.__init__.py file for windows.

    .pyenv\pyenv-win\versions\3.13.2\Lib\encodings\__init__.py

    if sys.platform == 'win32':
        # bpo-671666, bpo-46668: If Python does not implement a codec for current
        # Windows ANSI code page, use the "mbcs" codec instead:
        # WideCharToMultiByte() and MultiByteToWideChar() functions with CP_ACP.
        # Python does not support custom code pages.
        def _alias_mbcs(encoding):
            try:
                import _winapi
                ansi_code_page = "cp%s" % _winapi.GetACP()
                if encoding == ansi_code_page:
                    import encodings.mbcs
                    return encodings.mbcs.getregentry()
            except ImportError:
                # Imports may fail while we are shutting down
                pass
    
        codecs.register(_alias_mbcs)
    
    
  18. jcbrill commented on Jul 28, 2025

    @jcbrill
    Contributor

    For exposition purposes only, a simple example of using a platform-independent tempfile encoding symbol on windows.

    Feel free to ignore.

    Tested on Windows/cp1252 with Test€ in path.

    import sys
    
    #  If the tempfile encoding is a predefined sentinel value,
    #  use the windows ansi code page symbol for the tempfile
    #  encoding.
    #
    #  Using a sentinel symbol *might* allow PlatformIO/GNU Arm 
    #  response files to "work" on windows platforms without
    #  having to specify the actual python encoding name (e.g., "cp1252",
    #  "cp936", "gbk", etc.) which is user environment specific.
    #
    #  For example, "scons-ansi-codepage" could be a "virtual" encoding
    #  that maps to the current ansi code page *only on Windows*.
    
    ### SCons\Platform\__init__.py file-level code [Additions Begin]
    
    if sys.platform == 'win32':
    
        # Encoding symbols to map to windows current ansi codepage symbol
        _WINDOWS_USE_ANSI_CODEPAGE_SYMBOL = [
            # Any symbols that are **NOT** a python encoding/alias
            "scons-ansi-codepage",
            # **NOT NECESSARY AND CAN BE REMOVED** (prevents bytearray LookupError when passed through)
            "",                     
        ]
    
        import ctypes
        import ctypes.wintypes
    
        class _WinAPI:
    
            kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
    
            GetACP = kernel32.GetACP
            GetACP.argtypes = []
            GetACP.restype = ctypes.wintypes.UINT
    
            @classmethod
            def get_acp(cls):
                return cls.GetACP()
    
        def _tempfile_encoding(encoding):
            if encoding in _WINDOWS_USE_ANSI_CODEPAGE_SYMBOL:
                ansi_codepage = _WinAPI.get_acp()
                encoding = "cp" + str(ansi_codepage)
            return encoding
    else:
    
        # Needed for __main__ below not in production code
        _WINDOWS_USE_ANSI_CODEPAGE_SYMBOL = []
    
        def _tempfile_encoding(encoding):
            return encoding
    
    ### SCons\Platform\__init__.py file-level code [Additions End]
    
    class TempFileMunge:
    
        def __call__(self, target, source, env, for_signature):
    
            # for example
            args = ["test"]
    
            # TempFileMunge.__call__ [Changes Begin]
    
            join_char = env.get('TEMPFILEARGJOIN', ' ')
            encoding = _tempfile_encoding(env.get('TEMPFILEENCODING', 'utf-8'))  # <== NEW
            # os.write(fd, bytearray(join_char.join(args) + "\n", encoding))     # <== MODIFIED
            bytearray(join_char.join(args) + "\n", encoding)                     # <== EXAMPLE ONLY
    
            # TempFileMunge.__call__ [Changes End]
    
            # for example
            return encoding
    
    if __name__ == "__main__":
        
        tempfilemunge = TempFileMunge()
    
        for test in _WINDOWS_USE_ANSI_CODEPAGE_SYMBOL + ["utf-8", "gbk"]:
            env = {"TEMPFILEENCODING": test}
            print(f"encoding={test!r}, tempfile_encoding={tempfilemunge(None, None, env, None)!r}")

    Output:

    (3.13.2) S:\SCons\test-cp936\__CodePages>python example.py
    encoding='scons-ansi-codepage', tempfile_encoding='cp1252'
    encoding='', tempfile_encoding='cp1252'
    encoding='utf-8', tempfile_encoding='utf-8'
    encoding='gbk', tempfile_encoding='gbk'
    

    Changes above incorporated into PlatformIO/scons for testing.

    PlatformIO example usage:

    import sys
    Import("env")
    
    env["MAXLINELENGTH"] = 10
    if sys.platform == 'win32':
        env["TEMPFILEENCODING"] = "scons-ansi-codepage"
    
    print("--- EXTRASCRIPT:BEG -----")
    for key in ("MAXLINELENGTH", "TEMPFILEENCODING"):
        val = env.get(key)
        if val:
            print(f"env[{key!r}]={val!r}")
    print("--- EXTRASCRIPT:END -----")

    Output (Test€ in path):

    ...
    --- EXTRASCRIPT:BEG -----
    env['MAXLINELENGTH']=10
    env['TEMPFILEENCODING']='scons-ansi-codepage'
    --- EXTRASCRIPT:END -----
    ...
    

    Build successful.

    The project might "just work" when moving to other Windows machines with different default code pages and/or unicode paths without any changes.

    Not tested on cp936/gbk.

  19. mwichmann commented on Jul 28, 2025

    @mwichmann
    Collaborator

    Interesting. Waiting to see the feedback on the initial update to the PR, which takes the "don't guess" approach.

    You keep citing ansi, but we specifically had problems in the past with that not being "good enough". oem is noted as sometimes being used by console-based applications, which is the only variety we're talking to (like gcc and its linker). we're using oem for the Configure() case since it was introduced (which happened in 3.6). Microsoft recommends everyone to use Unicode now, obviously there are some holdouts (and, based on your earlier research, maybe mingw no longer is).

  20. jcbrill commented on Jul 28, 2025

    @jcbrill
    Contributor

    oem is noted as sometimes being used by console-based applications, which is the only variety we're talking to (like gcc and its linker).

    Reading/writing to and from a file and reading/writing to and from the console (e.g., stdout/stderr) are not necessarily the same thing.

    Otherwise, it would not have been possible to read files using console programs that were not in oem encoding which would have broken tempfile/utf-8 a long time ago.

    we're using oem for the Configure() case since it was introduced (which happened in 3.6).

    Searching for oem didn't turn up anything other than SCons/platform/win32.py and SCons/Tool/MSCommon/common.py. In both cases, oem was used to encode/decode content read from and/or written to stdout and stderr.

    If you have a reference for Configure(), I'm interested in the usage.

    It would make sense if the usage of oem was used in decoding captured stdout/stderr from a subprocess call or when writing to the console via stdout/stderr.

    Also, if all input/output is 7-bit ascii it's probably not going to matter which encoding is used.

    Microsoft recommends everyone to use Unicode now, obviously there are some holdouts (and, based on your earlier research, maybe mingw no longer is).

    My earlier research may be suspect. I'm not exactly sure where the PlatformIO builds come from so I don't know if there is a difference between the builds they use and the builds available via the arm site.

    Using the PlatformIO compilers outside of PlatformIO might be an interesting exercise.

    You keep citing ansi, but we specifically had problems in the past with that not being "good enough".

    It depends on what you're doing. For files, one has to know the expected encoding.

    For this particular issue, empirical evidence strongly suggests that the GNU Arm Embedded Compiler Toolchain is expecting the response file to be in cp1252 (ansi) rather than cp437 (oem) on a Windows/English (ansi=1252, oem=437) box.

    The PlatFormIO project was moved to a sub-directory of folder Testà. This directory was created using windows explorer.

    The character à was chosen on purpose: in cp1257 it is encoded as 0xe0 and in cp437 it is encoded as 0x85.

    Fragments for the cp1252 (ansi) and cp437 (oem) encodings:

               1252    437
    int byte   ansi    oem
    128 0x80    '€'    'Ç'
    ...
    133 0x85    '…'    'à'
    ...
    224 0xe0    'à'    'α'
    ...
    

    PlatformIO experiments:

    • PlatformIO ansi test (env["TEMPFILEENCODING"] = "cp1252") with Testà in project path:

      ...
      Linking .pio\build\bluepill_f103c6\firmware.elf
      Checking size .pio\build\bluepill_f103c6\firmware.elf
      Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
      RAM:   [=         ]  10.4% (used 1068 bytes from 10240 bytes)
      Flash: [==        ]  21.4% (used 7020 bytes from 32768 bytes)
      Building .pio\build\bluepill_f103c6\firmware.bin
      =========================================================================== [SUCCESS] Took 36.54 seconds ===========================================================================
      
    • Platform oem test (env["TEMPFILEENCODING"] = "oem") with Testà in project path:

      C:/Users/jbrill/.platformio/packages/toolchain-gccarmnoneeabi/bin/../lib/gcc/arm-none-eabi/14.2.1/../../../../arm-none-eabi/bin/ld.exe: cannot open map file C:/Users/jbrill/Desktop/Test\x85/firmware/.pio/build/bluepill_f103c6/firmware.map: No such file or directory
      collect2.exe: error: ld returned 1 exit status
      *** [.pio\build\bluepill_f103c6\firmware.elf] Error 1
      =========================================================================== [FAILED] Took 37.13 seconds ===========================================================================
      

      The error message contains Test\x85 which is Testà in 437 but Test… in 1252. Test… does not exist.

      Encoding aliases that elicit the same behavior include cp437 and ibm437.

    With regards to the updated PR documentation, are you sure the path to the response file is an issue?

    I'm not sure there is an issue from the command-line unless possibly the commands are redirected (see below).

    Folder 测试 was created in C:\Users and populated with a file (myresponsefile.txt) and populated with Hello, World!.

    From a Windows/English (1252/437) box, the following command-line invocations appear to work:

    S:\SCons\test-cp936>chcp
    Active code page: 437
    
    S:\SCons\test-cp936>type C:\Users\测试\myresponsefile.txt
    Hello, World!
    S:\SCons\test-cp936>
    

    I'm not saying there isn't an issue; just wondering if you had some tests that elicited undesirable behavior.

    The complete script characters.py to generate the character mappings is:

    import sys
    
    def write_stdout(msg):
        print(msg)
    
    def write_file(msg, fh):
        print(msg, file=fh)
    
    def write_output(msg, fh):
        write_stdout(msg)
        write_file(msg, fh)
    
    with open("bytechars.txt", "w", encoding="utf-8") as fh:
        write_output(f"int byte {'ansi':>6} {'oem':>6}", fh)
        for byte in range(128, 256):
            try:
                ansi = bytes([byte]).decode("cp1252")
            except UnicodeDecodeError:
                ansi = "??"
            try:
                oem = bytes([byte]).decode("cp437")
            except:
                oem = "??"
            write_output(f"{byte} 0x{byte:0x} {repr(ansi):>6} {repr(oem):>6}", fh)
    

    When run from the command-line, there is no issue:

    (3.13.2) S:\SCons\test-cp936>python characters.py
    ...
    

    However, when attempting to redirect stdout from the command-line there are errors printing to stdout:

    (3.13.2) S:\SCons\test-cp936>python characters.py >test.txt
    Traceback (most recent call last):
      File "S:\SCons\test-cp936\characters.py", line 24, in <module>
        write_output(f"{byte} 0x{byte:0x} {repr(ansi):>6} {repr(oem):>6}", fh)
        ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "S:\SCons\test-cp936\characters.py", line 10, in write_output
        write_stdout(msg)
        ~~~~~~~~~~~~^^^^^
      File "S:\SCons\test-cp936\characters.py", line 4, in write_stdout
        print(msg)
        ~~~~~^^^^^
      File "C:\Users\jbrill\.pyenv\pyenv-win\versions\3.13.2\Lib\encodings\cp1252.py", line 19, in encode
        return codecs.charmap_encode(input,self.errors,encoding_table)[0]
               ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    UnicodeEncodeError: 'charmap' codec can't encode character '\u20a7' in position 20: character maps to <undefined>
    

    Clear as mud?

  21. mwichmann commented on Jul 29, 2025

    @mwichmann
    Collaborator

    oem is noted as sometimes being used by console-based applications, which is the only variety we're talking to (like gcc and its linker).

    Reading/writing to and from a file and reading/writing to and from the console (e.g., stdout/stderr) are not necessarily the same thing.

    Yeah, okay. I've got decades of UNIX -> Linux work where they are explicitly the same, as they implement an "everything is a file" abstraction (streams are like files, with the exception that you can't seek on them). I forgot (and never do any Windows programming except for one brief assigned foray into C-sharp).

    Searching for oem didn't turn up anything other than SCons/platform/win32.py and SCons/Tool/MSCommon/common.py. In both cases, oem was used to encode/decode content read from and/or written to stdout and stderr.

    If you have a reference for Configure(), I'm interested in the usage.

    Configure is mentioned because it's the only current customer of PSPAWN, the alternate platform-specific routine that allows SCons to collect back the output of running a command, which it normally ignores. Configure runs small autogenerated test programs and SCons uses the results to decode what the result of those checks are, So it's exactly this:

    It would make sense if the usage of oem was used in decoding captured stdout/stderr from a subprocess call or when writing to the console via stdout/stderr.

    For the win32 platform, someone decided it was useful to implement multiple layers of functions for running a command, so spawn (the function that's stored in env['SPAWN'] for SCons to pick out at runtime) calls exec_spawn which calls spawnve - unless we're in the configure case, where it picks out env[PSPAWN] (which is piped_spawn on Windows) and uses it instead. This comment in SConf.py:

        def pspawn_wrapper(self, sh, escape, cmd, args, env):
            """Wrapper function for handling piped spawns.
    
            This looks to the calling interface (in Action.py) like a "normal"
            spawn, but associates the call with the PSPAWN variable from
            the construction environment and with the streams to which we
            want the output logged.  This gets slid into the construction
            environment as the SPAWN variable so Action.py doesn't have to
            know or care whether it's spawning a piped command or not.
            """

    It's, ummm, a bit grotty, admittedly. Nearly all of the crazy plumbing in win32.py should be replaceable by subprocess calls, which already have a mechanism to collect stdout/stderr - but it's such a fundamental part of how SCons runs on Windows it's scary to touch what's been duct-taped together for 20+ years with tons of mileage on it.

    Configure itself has stuff in the manpage

    And a gentler introduction in the User Guide

  22. jcbrill commented on Jul 29, 2025

    @jcbrill
    Contributor

    @mwichmann Suggested utility functions. Feel free to ignore.

    It might be helpful for users to add utility functions that return the active code page encoding strings (ansi and oem) on windows and return None for non-windows platforms. The Windows API functions are reasonably straightforward.

    Working skeleton code tested in a Windows/cp1252 VM with PlatformIO is shown below.

    The functions to retrieve the windows code page and return an encoding string could be added as the SCons\Util\windows.py module (skeleton code shown):

    # SPDX-License-Identifier: MIT
    #
    # Copyright The SCons Foundation
    
    """Microsoft Windows Utilities.
    """
    
    import sys
    
    if sys.platform == 'win32':
    
        import ctypes
        import ctypes.wintypes
    
        class _WinAPI:
    
            kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
    
            GetACP = kernel32.GetACP
            GetACP.argtypes = []
            GetACP.restype = ctypes.wintypes.UINT
    
            GetOEMCP = kernel32.GetOEMCP
            GetOEMCP.argtypes = []
            GetOEMCP.restype = ctypes.wintypes.UINT
            
        _remap_codepage_encoding = {
            "cp37": "cp037",  # IBM EBCDIC US-Canada
        }
    
        def get_windows_ansi_codepage_encoding():
            codepage = _WinAPI.GetACP()
            encoding = "cp" + str(codepage)
            encoding = _remap_codepage_encoding.get(encoding, encoding)
            return encoding
    
        def get_windows_oem_codepage_encoding():
            codepage = _WinAPI.GetOEMCP()
            encoding = "cp" + str(codepage)
            encoding = _remap_codepage_encoding.get(encoding, encoding)
            return encoding
    
    else:
    
        def get_windows_ansi_codepage_encoding():
            return None
    
        def get_windows_oem_codepage_encoding():
            return None
    
    # Local Variables:
    # tab-width:4
    # indent-tabs-mode:nil
    # End:
    # vim: set expandtab tabstop=4 shiftwidth=4:

    Patched into SCons\Util\__init__.py:

      from .filelock import FileLock, SConsLockFailure
    + from .windows import (
    +     get_windows_ansi_codepage_encoding,
    +     get_windows_oem_codepage_encoding,
    + )
      
      PYPY = hasattr(sys, 'pypy_translation_info')

    PlatformIO test configuration:

    • User folder: C:\Users\Userà
    • Project folder: C:\Users\Userà\Desktop\Testà\firmware
    • PlatformIO: C:\.platformio

    Unless I missed something, PlatformIO elected not to install into path C:\Users\Userà and instead installed to the root of C.

    PlatformIO sample project platformio.ini fragment:

    ...
    extra_scripts = tempfile_encoding.py
    

    PlaformIO sample project tempfile_encoding.py using the SCons\Util functions from above:

    import sys
    import SCons.Util
    
    Import("env")
    
    print("--- TEMPFILE_ENCODING:BEG -----")
    
    encoding_func = {
        "ansi": SCons.Util.get_windows_ansi_codepage_encoding,
        "oem": SCons.Util.get_windows_oem_codepage_encoding,
    }
    
    encoding_kind = "ansi"
    encoding = encoding_func[encoding_kind]()
    print(f"cfg: encoding={encoding!r}, encoding_kind={encoding_kind!r}")
    
    env["MAXLINELENGTH"] = 10
    if encoding:
        env["TEMPFILEENCODING"] = encoding
     
    for key in ("MAXLINELENGTH", "TEMPFILEENCODING"):
        val = env.get(key)
        if val:
            print(f"env[{key!r}]={val!r}")
    
    print("--- TEMPFILE_ENCODING:END -----")

    Sample output (get_windows_ansi_codepage_encoding()):

    ...
    Building in release mode
    --- TEMPFILE_ENCODING:BEG -----
    cfg: encoding='cp1252', encoding_kind='ansi'
    env['MAXLINELENGTH']=10
    env['TEMPFILEENCODING']='cp1252'
    --- TEMPFILE_ENCODING:END -----
    ...
    Linking .pio\build\bluepill_f103c6\firmware.elf
    Checking size .pio\build\bluepill_f103c6\firmware.elf
    Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
    RAM:   [=         ]  10.4% (used 1068 bytes from 10240 bytes)
    Flash: [==        ]  21.4% (used 7020 bytes from 32768 bytes)
    Building .pio\build\bluepill_f103c6\firmware.bin
    ===================================== [SUCCESS] Took 26.89 seconds =====================================
    

    Builds:

    • Success with get_windows_ansi_codepage_encoding (cp1252)
    • Failure with get_windows_oem_codepage_encoding (cp437).

    IMPORTANT NOTES:

    • The windows code page encoding string is constructed as "cp" + str(codepage).
    • Python does have codecs for all windows code page names. A user may have to manually specify the encoding when this happens.
  23. added a commit that references this issue on Jul 31, 2025
  24. jcbrill commented on Aug 1, 2025

    @jcbrill
    Contributor

    @mwichmann tempfile encoding with msvc response files.

    Preliminary indications are that msvc expects the response file to be utf-8-sig (utf-8 w/BOM) or the ansi codepage.

    This could all be wrong:

    • utf-8 with character points 128 and above seems to fail
    • utf-8-sig with character points 128 and above seems to pass
    • ansi codepage encoding with character points 128 and above supported by the code page seems to pass

    I surprised this hasn't come up before if the above is in fact the case.

    Definitely needs more testing.

  25. mwichmann commented on Aug 1, 2025

    @mwichmann
    Collaborator

    Historically we had trouble with German Visual Studio, which was fixed by the shift to oem encoding in the place that shift was made.

  26. jcbrill commented on Aug 1, 2025

    @jcbrill
    Contributor

    @mwichmann Response file (tempfile) example for testing.

    Attached is a simple SCons example of forcing response files with the MSVC compiler and different response file encodings and the corresponding build logs:
    msvc-test.zip

    Notes:

    • PYTHONIOENCODING=utf-8 is set in the batch file to eliminate encoding errors when printing from python.
    • The SConstruct is assuming TEMPFILEENCODING as the construction variable. Change as needed.
    • The local implementation will not match any of the PRs so the traceback origin will be slightly different.

    All SCons builds performed in a VM with Windows 11 (English, cp1252, cp437) and VS2022 English.

    The output logs contains examples of:

    • Build failures: msvc can't decode response file paths correctly
    • UnicodeEncodingError
    • LookupError
    • Errors attempting to remove the temporary file (possibly AV related)

    Should None ever be passed to bytearray/bytes, a TypeError is raised.

    The tracebacks are definitely not user friendly. None of these were going to happen when the encoding was hard-coded to utf-8.

    MSVC response file tests:

    • for each user: User, User€, Testà, 测试:
      <EXTRACTLOCATION>\msvc-test\run.bat
      
      Each log file contains the output of 24 builds:
      • for each symbol: ansi, utf-8-sig, locale, oem, default, badencodingname:
        • for each include folder: test, test€, testà, test测试:
          • build with SCons

    msvc-test.zip contents:

    247471 B msvc-test
      5308 B ├─ msvc
       111 B │  ├─ src
       111 B │  │  └─ main.c
      3513 B │  ├─ SConstruct
      1684 B │  └─ msvc.bat
        67 B ├─ test
        67 B │  └─ include
        67 B │     └─ macros.h
        67 B ├─ testà
        67 B │  └─ include
        67 B │     └─ macros.h
        67 B ├─ test€
        67 B │  └─ include
        67 B │     └─ macros.h
        67 B ├─ test测试
        67 B │  └─ include
        67 B │     └─ macros.h
     60105 B ├─ msvc-log-User.txt
     60521 B ├─ msvc-log-Userà.txt
     60617 B ├─ msvc-log-User€.txt
     60521 B ├─ msvc-log-测试.txt
       131 B └─ run.bat
    
    10 directories, 12 files

    To run locally:

    • Configure SCons location and Python executable in msvc-test\msvc\msvc.bat:
      @setlocal
      
      ::====== CONFIGURE SCONS AND PYTHON ====================
      
      @set "SCONS_ROOT=C:\scons\scons-tempfile"
      @set "PYTHON_EXE=C:\python-3.13.4-embed-amd64\python.exe"
      
      ::=======================================================
      
    • As written, run.bat must be run from the msvc-test directory:
      <EXTRACTLOCATION>\msvc-test> run
      
      This requirement can be fixed, but didn't feel like re-running all tests to be sure.

    Interestingly, experiment (user=测试, include=test测试, encoding=utf-8-sig) passes in an English VM:

    C:\Test\msvc-test\msvc>C:\python-3.13.4-embed-amd64\python.exe "C:\scons\scons-tempfile\scripts\scons.py" 
    scons: Reading SConscript files ...
    
    Environment variables:
      USERPROFILE:
        'C:\\Users\\测试'
        'C:\\Users\\测试' (abspath)
        'C:\\Users\\测试' (realpath)
      TEMP:
        'C:\\Users\\D147~1\\AppData\\Local\\Temp'
        'C:\\Users\\D147~1\\AppData\\Local\\Temp' (abspath)
        'C:\\Users\\测试\\AppData\\Local\\Temp' (realpath)
    
    Code pages:
      ansi: 'cp1252'
       oem: 'cp437'
    
    Test configuration:
      encoding: 'utf-8-sig' (encoding_alias='utf-8-sig')
       include: '#../test测试/include' (include_alias='test-cp936')
    
    env['MAXLINELENGTH']=10
    env['TEMPFILEENCODING']='utf-8-sig'
    
    scons: done reading SConscript files.
    scons: Building targets ...
    Using tempfile C:\Users\D147~1\AppData\Local\Temp\tmpowx948q2.lnk for command line:
    cl /Fosrc\main.obj /c src\main.c /nologo /IC:\Test\msvc-test\test测试\include
    cl @C:\Users\D147~1\AppData\Local\Temp\tmpowx948q2.lnk
    main.c
    Using tempfile C:\Users\D147~1\AppData\Local\Temp\tmpr7x0as3q.lnk for command line:
    link /nologo /OUT:src\main.exe src\main.obj
    link @C:\Users\D147~1\AppData\Local\Temp\tmpr7x0as3q.lnk
    scons: done building targets.
    

    If nothing else, it is easy enough to test the encoding changes with msvc.

    Similar tests using PlatformIO can be performed as well.

    Enjoy.

  27. added a commit that references this issue on Aug 3, 2025
  28. bdbaddog commented on Aug 3, 2025

    @bdbaddog
    Contributor

    The PR doesn't fix this issue automatically, but does allow the user to get on with their build by changing the encoding.
    I'm re-opening this Issue for the time being.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Op Sys: WindowsTEMPFILE

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions