You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
PlatformIO STM32 Build Fails on Windows Chinese Version: TMP File Encoding Issue #4746
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.
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.
After my debugging, I found that after writing the temporary file (which contains Chinese characters), the command is eventually executed via the spawnve method:
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.
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.
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.
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.
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.
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)
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.
importsys# 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]ifsys.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)"",
]
importctypesimportctypes.wintypesclass_WinAPI:
kernel32=ctypes.WinDLL("kernel32", use_last_error=True)
GetACP=kernel32.GetACPGetACP.argtypes= []
GetACP.restype=ctypes.wintypes.UINT@classmethoddefget_acp(cls):
returncls.GetACP()
def_tempfile_encoding(encoding):
ifencodingin_WINDOWS_USE_ANSI_CODEPAGE_SYMBOL:
ansi_codepage=_WinAPI.get_acp()
encoding="cp"+str(ansi_codepage)
returnencodingelse:
# Needed for __main__ below not in production code_WINDOWS_USE_ANSI_CODEPAGE_SYMBOL= []
def_tempfile_encoding(encoding):
returnencoding### SCons\Platform\__init__.py file-level code [Additions End]classTempFileMunge:
def__call__(self, target, source, env, for_signature):
# for exampleargs= ["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)) # <== MODIFIEDbytearray(join_char.join(args) +"\n", encoding) # <== EXAMPLE ONLY# TempFileMunge.__call__ [Changes End]# for examplereturnencodingif__name__=="__main__":
tempfilemunge=TempFileMunge()
fortestin_WINDOWS_USE_ANSI_CODEPAGE_SYMBOL+ ["utf-8", "gbk"]:
env= {"TEMPFILEENCODING": test}
print(f"encoding={test!r}, tempfile_encoding={tempfilemunge(None, None, env, None)!r}")
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).
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:
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:
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>
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:
defpspawn_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.
@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."""importsysifsys.platform=='win32':
importctypesimportctypes.wintypesclass_WinAPI:
kernel32=ctypes.WinDLL("kernel32", use_last_error=True)
GetACP=kernel32.GetACPGetACP.argtypes= []
GetACP.restype=ctypes.wintypes.UINTGetOEMCP=kernel32.GetOEMCPGetOEMCP.argtypes= []
GetOEMCP.restype=ctypes.wintypes.UINT_remap_codepage_encoding= {
"cp37": "cp037", # IBM EBCDIC US-Canada
}
defget_windows_ansi_codepage_encoding():
codepage=_WinAPI.GetACP()
encoding="cp"+str(codepage)
encoding=_remap_codepage_encoding.get(encoding, encoding)
returnencodingdefget_windows_oem_codepage_encoding():
codepage=_WinAPI.GetOEMCP()
encoding="cp"+str(codepage)
encoding=_remap_codepage_encoding.get(encoding, encoding)
returnencodingelse:
defget_windows_ansi_codepage_encoding():
returnNonedefget_windows_oem_codepage_encoding():
returnNone# 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')
@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.
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:
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.
Activity
bdbaddog commentedon Jul 15, 2025
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.
yehjf commentedon Jul 16, 2025
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
bdbaddog commentedon Jul 16, 2025
@yehjf what does the following python code output on your system
yehjf commentedon Jul 16, 2025
Display
utf-8After my debugging, I found that after writing the temporary file (which contains Chinese characters), the command is eventually executed via the spawnve method:
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.
mwichmann commentedon Jul 16, 2025
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.
bdbaddog commentedon Jul 16, 2025
yehjf commentedon Jul 17, 2025
bdbaddog commentedon Jul 17, 2025
How about try this:
yehjf commentedon Jul 17, 2025
mwichmann commentedon Jul 19, 2025
To some of the above:
sys.getdefaultencoding()is not useful, it's defined to returnutf-8these days. That's for Python.locale.getencoding()is far more interesting.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.
jcbrill commentedon Jul 20, 2025
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.
mwichmann commentedon Jul 20, 2025
I've done that too, but it needs to be a different enough locale to trigger the problem.
59 remaining items
jcbrill commentedon Jul 27, 2025
Yes. Automatically changing the encoding from
utf-8is just asking for trouble.That particular encoding error was unexpected.
Windows paths are effectively
utf-16which is a large candidate set of characters and target encodings may accept a significantly smaller set of characters. Converting toutf-8is largely going to be successful.Single byte encodings like
cp1252andcp437are going to haveUnicodeErrors 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.
jcbrill commentedon Jul 28, 2025
@mwichmann Interesting code at bottom of py 3.13.2
encodings.__init__.pyfile for windows..pyenv\pyenv-win\versions\3.13.2\Lib\encodings\__init__.pyjcbrill commentedon Jul 28, 2025
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.Output:
Changes above incorporated into PlatformIO/scons for testing.
PlatformIO example usage:
Output (
Test€in path):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.mwichmann commentedon Jul 28, 2025
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).
jcbrill commentedon Jul 28, 2025
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
oemencoding which would have broken tempfile/utf-8 a long time ago.Searching for
oemdidn't turn up anything other thanSCons/platform/win32.pyandSCons/Tool/MSCommon/common.py. In both cases,oemwas used to encode/decode content read from and/or written tostdoutandstderr.If you have a reference for Configure(), I'm interested in the usage.
It would make sense if the usage of
oemwas 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.
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.
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 thancp437(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: incp1257it is encoded as0xe0and incp437it is encoded as0x85.Fragments for the
cp1252(ansi) andcp437(oem) encodings:PlatformIO experiments:
PlatformIO ansi test (
env["TEMPFILEENCODING"] = "cp1252") withTestàin project path:Platform oem test (
env["TEMPFILEENCODING"] = "oem") withTestàin project path:The error message contains
Test\x85which isTestàin437butTest…in1252.Test…does not exist.Encoding aliases that elicit the same behavior include
cp437andibm437.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 inC:\Usersand populated with a file (myresponsefile.txt) and populated withHello, World!.From a Windows/English (1252/437) box, the following command-line invocations appear to work:
I'm not saying there isn't an issue; just wondering if you had some tests that elicited undesirable behavior.
The complete script
characters.pyto generate the character mappings is:When run from the command-line, there is no issue:
However, when attempting to redirect stdout from the command-line there are errors printing to stdout:
Clear as mud?
mwichmann commentedon Jul 29, 2025
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).
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: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 inenv['SPAWN']for SCons to pick out at runtime) callsexec_spawnwhich callsspawnve- unless we're in the configure case, where it picks outenv[PSPAWN](which ispiped_spawnon Windows) and uses it instead. This comment inSConf.py: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
jcbrill commentedon Jul 29, 2025
@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
Nonefor 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.pymodule (skeleton code shown):Patched into
SCons\Util\__init__.py:PlatformIO test configuration:
C:\Users\UseràC:\Users\Userà\Desktop\Testà\firmwareC:\.platformioUnless I missed something, PlatformIO elected not to install into path
C:\Users\Useràand instead installed to the root ofC.PlatformIO sample project
platformio.inifragment:PlaformIO sample project
tempfile_encoding.pyusing theSCons\Utilfunctions from above:Sample output (
get_windows_ansi_codepage_encoding()):Builds:
get_windows_ansi_codepage_encoding(cp1252)get_windows_oem_codepage_encoding(cp437).IMPORTANT NOTES:
"cp" + str(codepage).Fix Issue #4746 by changing encoding of tempfile's to use locale.getp…
jcbrill commentedon Aug 1, 2025
@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-8with character points 128 and above seems to failutf-8-sigwith character points 128 and above seems to passI surprised this hasn't come up before if the above is in fact the case.
Definitely needs more testing.
mwichmann commentedon Aug 1, 2025
Historically we had trouble with German Visual Studio, which was fixed by the shift to oem encoding in the place that shift was made.
jcbrill commentedon Aug 1, 2025
@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-8is set in the batch file to eliminate encoding errors when printing from python.TEMPFILEENCODINGas the construction variable. Change as needed.All SCons builds performed in a VM with Windows 11 (English, cp1252, cp437) and VS2022 English.
The output logs contains examples of:
UnicodeEncodingErrorLookupErrorShould
Noneever be passed tobytearray/bytes, aTypeErroris 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:
User,User€,Testà,测试:ansi,utf-8-sig,locale,oem,default,badencodingname:test,test€,testà,test测试: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 filesTo run locally:
msvc-test\msvc\msvc.bat:run.batmust be run from themsvc-testdirectory:Interestingly, experiment (user=
测试, include=test测试, encoding=utf-8-sig) passes in an English VM:If nothing else, it is easy enough to test the encoding changes with msvc.
Similar tests using PlatformIO can be performed as well.
Enjoy.
Merge pull request #4749 from bdbaddog/fix_4746_TEMPFILE_ENC_ISSUE
bdbaddog commentedon Aug 3, 2025
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.