python / cpython

The Python programming language
https://www.python.org
Other
62.46k stars 29.98k forks source link

[Windows] Embedded Python Memory Leaks #96853

Closed AlexSoft73 closed 1 year ago

AlexSoft73 commented 2 years ago

Hi dear Python team,

I am a building a c/c++ application for general purpose and I would like to have in the application the possibility of running “Python” scripting code. Python has proved to be a good programming language to deal with heavy Math as in AI.

Now when I embed Python in my application things go perfect, except for memory leaks! As a sample by just issuing the following code leaves memory leaks of around (2Mb):

define PY_SSIZE_T_CLEAN

define Py_LIMITED_API 0x03000000

include

pragma comment (lib,"python3.lib")

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) { Py_InitializeEx(0); //For Embeded Python Py_FinalizeEx(); ..More code.. return 0; } Is there something I must do to cause Python to release all resources allocated

AlexSoft73 commented 2 years ago

Thanks in advance

sweeneyde commented 2 years ago

I believe this is fixed in Python 3.11, and was tracked by https://github.com/python/cpython/issues/44470. I doubt there would be a backport, since by my understanding, much of the work to fix this was rather involved.

cc @vstinner

AlexSoft73 commented 2 years ago

I am actually using Python 3.11 and it is happening. It will be of a tremendous help to see that fixed.

vstinner commented 2 years ago

..More code..

Can you please provide a full reproducer? Like a whole C file which reproduces the issue? If possible, a regular main() function, not a "WINAPI wWinMain" function.

Can you reproduce the issue on other operating systems? How do you link your program?

AlexSoft73 commented 2 years ago

Thanks a lot for your support.

I am assuming your environment of work is Unix/Linux, I cannot speak about memory leaks in Unix environment since I am not working performing my tests in this unix environment.

The code I sent is what it is, it is that simple:

//This is the main entry point for a C/C++ code copiled for Windows 64bit in Microsoft Visual Studio 2029 //int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) int main(...) { Py_InitializeEx(0); Py_FinalizeEx(); Py_InitializeEx(0); Py_FinalizeEx(); return 0; }

Put a comment in that line and add the main prototype your compliler/linker likes. Trace that code and you will see how memory leaks.

I repeat, this memory leaks might not happen in Unix/Linux environment, I suggest testing this code in windows enviroment and Python 3.11

Thanks a million, Alexei

PD: If you have and have permission to share the original code for Py_InitializeEx and Py_FinalizeEx send the code to me and I will help you in troubleshooting this code for Windows


De: Victor Stinner @.> Enviado: lunes, 19 de septiembre de 2022 09:51 p. m. Para: python/cpython @.> CC: AlexSoft73 @.>; Author @.> Asunto: Re: [python/cpython] Embedded Python Memory Leaks (Issue #96853)

..More code..

Can you please provide a full reproducer? Like a whole C file which reproduces the issue? If possible, a regular main() function, not a "WINAPI wWinMain" function.

Can you reproduce the issue on other operating systems? How do you link your program?

— Reply to this email directly, view it on GitHubhttps://github.com/python/cpython/issues/96853#issuecomment-1251600183, or unsubscribehttps://github.com/notifications/unsubscribe-auth/A3C7TGERMLZNFLTC3MUHF2DV7DN6XANCNFSM6AAAAAAQNW7ZHA. You are receiving this because you authored the thread.Message ID: @.***>

AlexSoft73 commented 2 years ago

Thanks for your reply,

Well, i am testing my code with Python 3.11 (64bits), the latest version available and it is leaking memory.

I read the whole #44470 and could not find even the reason for that. if you have the code and have permissio to share it, send me the source code for Py_InitializeEx and Py_FinalizeEx to see If I can help you in troubleshooting the memory leaks.

Thanks in advance, Alexei


De: Dennis Sweeney @.> Enviado: viernes, 16 de septiembre de 2022 09:03 p. m. Para: python/cpython @.> CC: AlexSoft73 @.>; Author @.> Asunto: Re: [python/cpython] Embedded Python Memory Leaks (Issue #96853)

I believe this is fixed in Python 3.11, and was tracked by #44470https://github.com/python/cpython/issues/44470. I doubt there would be a backport, since by my understanding, much of the work to fix this was rather involved.

cc @vstinnerhttps://github.com/vstinner

— Reply to this email directly, view it on GitHubhttps://github.com/python/cpython/issues/96853#issuecomment-1249815679, or unsubscribehttps://github.com/notifications/unsubscribe-auth/A3C7TGDYEICQQOT5OXTTTT3V6TODNANCNFSM6AAAAAAQNW7ZHA. You are receiving this because you authored the thread.Message ID: @.***>

da-woods commented 2 years ago

It's open source - you don't need permission to see the code for PyInitializeEx and Py_FinalizeEx. You can read it here https://github.com/python/cpython/blob/4e4bfffe2ded7339663945ad4c494db0e88ec96c/Python/pylifecycle.c#L1274

AlexSoft73 commented 2 years ago

Thanks a lot for the info, I am working on it to see if I can help you guys.

AlexSoft73 commented 2 years ago

I cannot seem to find all files references in "pylifecycle.c" Where are these files:

include "pycore_bytesobject.h" // _PyBytes_InitTypes()

include "pycore_ceval.h" // _PyEval_FiniGIL()

include "pycore_context.h" // _PyContext_Init()

include "pycore_exceptions.h" // _PyExc_InitTypes()

include "pycore_dict.h" // _PyDict_Fini()

include "pycore_fileutils.h" // _Py_ResetForceASCII()

include "pycore_floatobject.h" // _PyFloat_InitTypes()

include "pycore_genobject.h" // _PyAsyncGen_Fini()

include "pycore_import.h" // _PyImport_BootstrapImp()

include "pycore_initconfig.h" // _PyStatus_OK()

include "pycore_list.h" // _PyList_Fini()

include "pycore_long.h" // _PyLong_InitTypes()

include "pycore_object.h" // _PyDebug_PrintTotalRefs()

include "pycore_pathconfig.h" // _PyConfig_WritePathConfig()

include "pycore_pyerrors.h" // _PyErr_Occurred()

include "pycore_pylifecycle.h" // _PyErr_Print()

include "pycore_pymem.h" // _PyObject_DebugMallocStats()

include "pycore_pystate.h" // _PyThreadState_GET()

include "pycore_runtime.h" // _Py_ID()

include "pycore_runtime_init.h" // _PyRuntimeState_INIT

include "pycore_sliceobject.h" // _PySlice_Fini()

include "pycore_sysmodule.h" // _PySys_ClearAuditHooks()

include "pycore_traceback.h" // _Py_DumpTracebackThreads()

include "pycore_tuple.h" // _PyTuple_InitTypes()

include "pycore_typeobject.h" // _PyTypes_InitTypes()

include "pycore_unicodeobject.h" // _PyUnicode_InitTypes()

ericsnowcurrently commented 2 years ago

They are in Include/internal.

AlexSoft73 commented 2 years ago

Hi Python team,

I'd like to compile the python source code in VS2019 to try and debug the initialization process, hence be able to signal what is not release when python is called to finalized. Is there an easy way of getting all files (.h,.c,.cpp.,...) required for this

da-woods commented 2 years ago

@AlexSoft73 there's some information about how to download and compile Python at the top of this page https://devguide.python.org/

AlexSoft73 commented 1 year ago

Yes, I saw it, I am trying to do it to find the reason for those memory leaks and let you knoqw guys

thanks


De: da-woods @.> Enviado: sábado, 24 de septiembre de 2022 06:36 a. m. Para: python/cpython @.> CC: AlexSoft73 @.>; Mention @.> Asunto: Re: [python/cpython] Embedded Python Memory Leaks (Issue #96853)

@AlexSoft73https://github.com/AlexSoft73 there's some information about how to download and compile Python at the top of this page https://devguide.python.org/

— Reply to this email directly, view it on GitHubhttps://github.com/python/cpython/issues/96853#issuecomment-1256880528, or unsubscribehttps://github.com/notifications/unsubscribe-auth/A3C7TGAH5PVUCRE7MYIYQQDV72ONDANCNFSM6AAAAAAQNW7ZHA. You are receiving this because you were mentioned.Message ID: @.***>

AlexSoft73 commented 1 year ago

For some reason I am having no luck in this:

Git Error:

ssh: connect to host github.com port 22: Connection timed out fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

I am behind a proxy


De: da-woods @.> Enviado: sábado, 24 de septiembre de 2022 06:36 a. m. Para: python/cpython @.> CC: AlexSoft73 @.>; Mention @.> Asunto: Re: [python/cpython] Embedded Python Memory Leaks (Issue #96853)

@AlexSoft73https://github.com/AlexSoft73 there's some information about how to download and compile Python at the top of this page https://devguide.python.org/

— Reply to this email directly, view it on GitHubhttps://github.com/python/cpython/issues/96853#issuecomment-1256880528, or unsubscribehttps://github.com/notifications/unsubscribe-auth/A3C7TGAH5PVUCRE7MYIYQQDV72ONDANCNFSM6AAAAAAQNW7ZHA. You are receiving this because you were mentioned.Message ID: @.***>

AlexSoft73 commented 1 year ago

Hi dear python team,

when compiling in VS2019 I get the following error:

[error] 2>D:\Python\Source\cpython-main\Modules_ctypes\callproc.c(82,10): fatal error C1083: Cannot open include file: 'ffi.h': No such file or directory [/error]

I searched for this file I I cannot locate it, where can I find it please

thanks in advance

AlexSoft73 commented 1 year ago

Good day Python Team,

I cannot get the python312.dll built (this is my file of interest to troubleshoot the memory leaks)

Thanks in advance, Alexei

Here I am posting the whole log for python solution (PCbuild.sln) built in VS2019: ``` **1>------ Rebuild All started: Project: _freeze_module, Configuration: Debug x64 ------ 2>------ Rebuild All started: Project: pyshellext, Configuration: Debug x64 ------ 3>------ Rebuild All started: Project: sqlite3, Configuration: Debug x64 ------ 4>------ Rebuild All started: Project: python3dll, Configuration: Debug x64 ------ 2>pyshellext.cpp 4>python3dll.c 3>sqlite3.c 4> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\python3_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\python3_d.exp 3> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\sqlite3_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\sqlite3_d.exp 4>python3dll.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\python3_d.dll 5>------ Rebuild All started: Project: liblzma, Configuration: Debug x64 ------ 1>_freeze_module.c 1>config_minimal.c 1>atexitmodule.c 1>faulthandler.c 1>gcmodule.c 1>getbuildinfo.c 1>getpath_noop.c 1>posixmodule.c 1>signalmodule.c 1>_tracemalloc.c 1>_iomodule.c 1>bufferedio.c 1>bytesio.c 1>fileio.c 1>iobase.c 1>stringio.c 1>textio.c 1>winconsoleio.c 1>abstract.c 1>boolobject.c 1>bytearrayobject.c 1>bytes_methods.c 1>bytesobject.c 1>call.c 1>capsule.c 1>cellobject.c 1>classobject.c 1>codeobject.c 1>perf_trampoline.c 1>complexobject.c 1>descrobject.c 2> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\pyshellext_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\pyshellext_d.exp 2>pyshellext.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\pyshellext_d.dll 3>sqlite3.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\sqlite3_d.dll 6>------ Rebuild All started: Project: pylauncher, Configuration: Debug x64 ------ 7>------ Skipped Rebuild All: Project: xxlimited, Configuration: Release x64 ------ 7>Project not selected to build for this solution configuration 8>------ Rebuild All started: Project: venvlauncher, Configuration: Debug x64 ------ 6>launcher2.c 1>dictobject.c 1>enumobject.c 1>exceptions.c 1>fileobject.c 1>floatobject.c 1>frameobject.c 1>funcobject.c 1>genericaliasobject.c 1>genobject.c 1>interpreteridobject.c 1>iterobject.c 1>listobject.c 1>longobject.c 1>memoryobject.c 1>methodobject.c 1>moduleobject.c 1>namespaceobject.c 1>object.c 1>obmalloc.c 1>odictobject.c 1>picklebufobject.c 1>rangeobject.c 1>setobject.c 1>sliceobject.c 1>structseq.c 1>tupleobject.c 8>launcher.c 1>typeobject.c 1>unicodectype.c 1>unicodeobject.c 1>unionobject.c 1>weakrefobject.c 1>myreadline.c 1>parser.c 1>peg_api.c 1>pegen.c 1>pegen_errors.c 1>action_helpers.c 1>string_parser.c 1>token.c 1>tokenizer.c 1>invalid_parameter_handler.c 1>msvcrtmodule.c 1>winreg.c 1>_warnings.c 1>asdl.c 5>tuklib_cpucores.c 5>tuklib_physmem.c 5>check.c 5>crc32_fast.c 5>crc32_table.c 5>crc64_fast.c 5>crc64_table.c 5>sha256.c 5>alone_decoder.c 5>alone_encoder.c 5>auto_decoder.c 5>block_buffer_decoder.c 5>block_buffer_encoder.c 5>block_decoder.c 5>block_encoder.c 5>block_header_decoder.c 5>block_header_encoder.c 5>block_util.c 5>common.c 5>easy_buffer_encoder.c 5>easy_decoder_memusage.c 1>ast.c 1>ast_opt.c 1>ast_unparse.c 1>bltinmodule.c 1>bootstrap_hash.c 1>ceval.c 1>codecs.c 1>compile.c 1>context.c 1>dtoa.c 1>dynamic_annotations.c 1>dynload_win.c 1>errors.c 1>fileutils.c 1>formatter_unicode.c 1>frame.c 6>pylauncher.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\py_d.exe 9>------ Rebuild All started: Project: pywlauncher, Configuration: Debug x64 ------ 5>easy_encoder.c 1>future.c 1>getargs.c 1>getcompiler.c 1>getcopyright.c 1>getopt.c 1>getplatform.c 1>getversion.c 1>ceval_gil.c 5>easy_encoder_memusage.c 5>easy_preset.c 5>filter_buffer_decoder.c 5>filter_buffer_encoder.c 5>filter_common.c 1>hamt.c 1>hashtable.c 1>import.c 8>venvlauncher.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\venvlauncher_d.exe 10>------ Rebuild All started: Project: venvwlauncher, Configuration: Debug x64 ------ 5>filter_decoder.c 5>filter_encoder.c 5>filter_flags_decoder.c 5>filter_flags_encoder.c 5>hardware_cputhreads.c 5>hardware_physmem.c 5>index.c 5>index_decoder.c 5>index_encoder.c 1>importdl.c 1>initconfig.c 1>marshal.c 1>modsupport.c 1>mysnprintf.c 1>mystrtoul.c 1>pathconfig.c 1>preconfig.c 1>pyarena.c 1>pyctype.c 1>pyfpe.c 1>pyhash.c 1>pylifecycle.c 1>pymath.c 1>pystate.c 1>pystrcmp.c 1>pystrhex.c 5>index_hash.c 5>outqueue.c 5>stream_buffer_decoder.c 5>stream_buffer_encoder.c 5>stream_decoder.c 5>stream_encoder.c 5>stream_encoder_mt.c 5>stream_flags_common.c 5>stream_flags_decoder.c 5>stream_flags_encoder.c 5>vli_decoder.c 5>vli_encoder.c 5>vli_size.c 5>delta_common.c 9>launcher2.c 1>pystrtod.c 5>delta_decoder.c 5>delta_encoder.c 5>fastpos_table.c 5>lzma2_decoder.c 5>lzma2_encoder.c 1>Python-ast.c 1>pythonrun.c 1>Python-tokenize.c 1>pytime.c 10>launcher.c 5>lzma_decoder.c 5>lzma_encoder.c 5>lzma_encoder_optimum_fast.c 1>specialize.c 5>lzma_encoder_optimum_normal.c 1>structmember.c 5>lzma_encoder_presets.c 1>suggestions.c 5>lz_decoder.c 1>symtable.c 5>lz_encoder.c 1>thread.c 5>lz_encoder_mf.c 5>price_table.c 5>arm.c 1>traceback.c 5>armthumb.c 5>ia64.c 5>powerpc.c 5>simple_coder.c 5>simple_decoder.c 5>simple_encoder.c 5>sparc.c 5>x86.c 10>venvwlauncher.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\venvwlauncher_d.exe 9>pywlauncher.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\pyw_d.exe 1>sysmodule.c 5>liblzma.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\liblzma_d.lib 1> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_freeze_module_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_freeze_module_d.exp 1>_freeze_module.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_freeze_module_d.exe 1>Updated files: importlib._bootstrap.h, importlib._bootstrap_external.h, zipimport.h, abc.h, codecs.h, io.h, _collections_abc.h, _sitebuiltins.h, genericpath.h, ntpath.h, posixpath.h, os.h, site.h, stat.h, importlib.util.h, importlib.machinery.h, runpy.h, __hello__.h, __phello__.h, __phello__.ham.h, __phello__.ham.eggs.h, __phello__.spam.h, frozen_only.h 1>Updated files: getpath.h 1>"D:\Python\Source\cpython-main\PCbuild\\..\externals\pythonx86\tools\python.exe" 1>Using PythonForBuild="D:\Python\Source\cpython-main\PCbuild\\..\externals\pythonx86\tools\python.exe" 1>Error processing line 1 of C:\Python\Python311\Lib\site-packages\matplotlib-3.6.0-py3.11-nspkg.pth: 1> 1>EXEC : Fatal Python error : init_import_site: Failed to import the site module 1>Python runtime state: initialized 1>Traceback (most recent call last): 1> File "C:\Python\Python311\lib\site.py", line 186, in addpackage 1> exec(line) 1> File "", line 1, in 1> File "C:\Python\Python311\lib\importlib\machinery.py", line 15, in 1> from ._bootstrap_external import NamespaceLoader 1>ImportError: cannot import name 'NamespaceLoader' from 'importlib._bootstrap_external' (C:\Python\Python311\lib\importlib\_bootstrap_external.py) 1> 1>During handling of the above exception, another exception occurred: 1> 1>Traceback (most recent call last): 1> File "C:\Python\Python311\lib\site.py", line 616, in 1> main() 1> File "C:\Python\Python311\lib\site.py", line 603, in main 1> known_paths = addsitepackages(known_paths) 1> File "C:\Python\Python311\lib\site.py", line 384, in addsitepackages 1> addsitedir(sitedir, known_paths) 1> File "C:\Python\Python311\lib\site.py", line 226, in addsitedir 1> addpackage(sitedir, name, known_paths) 1> File "C:\Python\Python311\lib\site.py", line 196, in addpackage 1> import traceback 1> File "C:\Python\Python311\lib\traceback.py", line 5, in 1> import linecache 1> File "C:\Python\Python311\lib\linecache.py", line 11, in 1> import tokenize 1> File "C:\Python\Python311\lib\tokenize.py", line 33, in 1> import re 1> File "C:\Python\Python311\lib\re\__init__.py", line 125, in 1> from . import _compiler, _parser 1> File "C:\Python\Python311\lib\re\_compiler.py", line 18, in 1> assert _sre.MAGIC == MAGIC, "SRE module mismatch" 1>AssertionError: SRE module mismatch 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: The command ""D:\Python\Source\cpython-main\PCbuild\\..\externals\pythonx86\tools\python.exe" "D:\Python\Source\cpython-main\Tools\scripts\deepfreeze.py" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\importlib._bootstrap.h:importlib._bootstrap" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\importlib._bootstrap_external.h:importlib._bootstrap_external" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\zipimport.h:zipimport" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\abc.h:abc" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\codecs.h:codecs" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\io.h:io" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\_collections_abc.h:_collections_abc" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\_sitebuiltins.h:_sitebuiltins" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\genericpath.h:genericpath" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\ntpath.h:ntpath" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\posixpath.h:posixpath" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\os.h:os" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\site.h:site" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\stat.h:stat" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\importlib.util.h:importlib.util" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\importlib.machinery.h:importlib.machinery" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\runpy.h:runpy" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__hello__.h:__hello__" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__phello__.h:__phello__" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__phello__.ham.h:__phello__.ham" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__phello__.ham.eggs.h:__phello__.ham.eggs" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__phello__.spam.h:__phello__.spam" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\frozen_only.h:frozen_only" ^ 1>D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "-o" "D:\Python\Source\cpython-main\Python\deepfreeze\deepfreeze.c"" exited with code 1. 1>Done building project "_freeze_module.vcxproj" -- FAILED. 11>------ Rebuild All started: Project: pythoncore, Configuration: Debug x64 ------ 11>Killing any running python_d.exe instances... 11>"D:\Python\Source\cpython-main\PCbuild\\..\externals\pythonx86\tools\python.exe" 11>Using PythonForBuild="D:\Python\Source\cpython-main\PCbuild\\..\externals\pythonx86\tools\python.exe" 11>Regenerate Global Objects 11>Error processing line 1 of C:\Python\Python311\Lib\site-packages\matplotlib-3.6.0-py3.11-nspkg.pth: 11> 11>EXEC : Fatal Python error : init_import_site: Failed to import the site module 11>Python runtime state: initialized 11>Traceback (most recent call last): 11> File "C:\Python\Python311\lib\site.py", line 186, in addpackage 11> exec(line) 11> File "", line 1, in 11> File "C:\Python\Python311\lib\importlib\machinery.py", line 15, in 11> from ._bootstrap_external import NamespaceLoader 11>ImportError: cannot import name 'NamespaceLoader' from 'importlib._bootstrap_external' (C:\Python\Python311\lib\importlib\_bootstrap_external.py) 11> 11>During handling of the above exception, another exception occurred: 11> 11>Traceback (most recent call last): 11> File "C:\Python\Python311\lib\site.py", line 616, in 11> main() 11> File "C:\Python\Python311\lib\site.py", line 603, in main 11> known_paths = addsitepackages(known_paths) 11> File "C:\Python\Python311\lib\site.py", line 384, in addsitepackages 11> addsitedir(sitedir, known_paths) 11> File "C:\Python\Python311\lib\site.py", line 226, in addsitedir 11> addpackage(sitedir, name, known_paths) 11> File "C:\Python\Python311\lib\site.py", line 196, in addpackage 11> import traceback 11> File "C:\Python\Python311\lib\traceback.py", line 5, in 11> import linecache 11> File "C:\Python\Python311\lib\linecache.py", line 11, in 11> import tokenize 11> File "C:\Python\Python311\lib\tokenize.py", line 33, in 11> import re 11> File "C:\Python\Python311\lib\re\__init__.py", line 125, in 11> from . import _compiler, _parser 11> File "C:\Python\Python311\lib\re\_compiler.py", line 18, in 11> assert _sre.MAGIC == MAGIC, "SRE module mismatch" 11>AssertionError: SRE module mismatch 11>D:\Python\Source\cpython-main\PCbuild\regen.targets(88,5): error MSB3073: The command ""D:\Python\Source\cpython-main\PCbuild\\..\externals\pythonx86\tools\python.exe" Tools\scripts\generate_global_objects.py" exited with code 1. 11>Done building project "pythoncore.vcxproj" -- FAILED. 12>------ Rebuild All started: Project: _socket, Configuration: Debug x64 ------ 13>------ Rebuild All started: Project: _ctypes, Configuration: Debug x64 ------ 14>------ Rebuild All started: Project: _elementtree, Configuration: Debug x64 ------ 15>------ Rebuild All started: Project: _msi, Configuration: Debug x64 ------ 14>_elementtree.c 14>xmlparse.c 14>xmlrole.c 14>xmltok.c 15>_msi.c 12>socketmodule.c 13>_ctypes.c 13>callbacks.c 13>callproc.c 13>cfield.c 13>malloc_closure.c 13>stgdict.c 12> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_socket_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_socket_d.exp 14> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_elementtree_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_elementtree_d.exp 15> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_msi_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_msi_d.exp 13> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_ctypes_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_ctypes_d.exp 14>_elementtree.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_elementtree_d.pyd 15>_msi.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_msi_d.pyd 13>_ctypes.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_ctypes_d.pyd 12>_socket.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_socket_d.pyd 16>------ Rebuild All started: Project: _decimal, Configuration: Debug x64 ------ 17>------ Rebuild All started: Project: _sqlite3, Configuration: Debug x64 ------ 18>------ Rebuild All started: Project: _ssl, Configuration: Debug x64 ------ 19>------ Rebuild All started: Project: _testcapi, Configuration: Debug x64 ------ 16>Performing Custom Build Tools 16> Assembling: D:\Python\Source\cpython-main\Modules\_decimal\libmpdec\vcdiv64.asm 16>_decimal.c 16>basearith.c 18>_ssl.c 16>constants.c 16>context.c 16>convolute.c 17>connection.c 16>crt.c 17>cursor.c 17>microprotocols.c 16>difradix2.c 17>module.c 16>fnt.c 16>fourstep.c 17>prepare_protocol.c 16>io.c 16>mpalloc.c 17>row.c 16>mpdecimal.c 19>_testcapimodule.c 19>vectorcall.c 19>vectorcall_limited.c 19>heaptype.c 19>unicode.c 17>statement.c 17>util.c 16>numbertheory.c 16>sixstep.c 17>blob.c 16>transpose.c 18>applink.c 19> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_testcapi_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_testcapi_d.exp 16> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_decimal_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_decimal_d.exp 19>_testcapi.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_testcapi_d.pyd 16>_decimal.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_decimal_d.pyd 20>------ Rebuild All started: Project: _testinternalcapi, Configuration: Debug x64 ------ 21>------ Rebuild All started: Project: _testimportmultiple, Configuration: Debug x64 ------ 17> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_sqlite3_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_sqlite3_d.exp 18> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_ssl_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_ssl_d.exp 21>_testimportmultiple.c 20>_testinternalcapi.c 17>_sqlite3.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_sqlite3_d.pyd 22>------ Rebuild All started: Project: _tkinter, Configuration: Debug x64 ------ 21> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_testimportmultiple_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_testimportmultiple_d.exp 18>_ssl.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_ssl_d.pyd 22>_tkinter.c 22>tkappinit.c 20> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_testinternalcapi_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_testinternalcapi_d.exp 21>_testimportmultiple.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_testimportmultiple_d.pyd 23>------ Rebuild All started: Project: _bz2, Configuration: Debug x64 ------ 23>_bz2module.c 23>blocksort.c 23>bzlib.c 23>compress.c 20>_testinternalcapi.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_testinternalcapi_d.pyd 24>------ Rebuild All started: Project: _lzma, Configuration: Debug x64 ------ 23>crctable.c 24>_lzmamodule.c 23>decompress.c 25>------ Rebuild All started: Project: unicodedata, Configuration: Debug x64 ------ 23>huffman.c 23>randtable.c 22> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_tkinter_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_tkinter_d.exp 25>unicodedata.c 23> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_bz2_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_bz2_d.exp 22>_tkinter.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_tkinter_d.pyd 23>_bz2.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_bz2_d.pyd 26>------ Rebuild All started: Project: pyexpat, Configuration: Debug x64 ------ 27>------ Rebuild All started: Project: _hashlib, Configuration: Debug x64 ------ 26>pyexpat.c 26>xmlparse.c 26>xmlrole.c 26>xmltok.c 24> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_lzma_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_lzma_d.exp 27>_hashopenssl.c 27> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_hashlib_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_hashlib_d.exp 24>_lzma.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_lzma_d.pyd 26> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\pyexpat_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\pyexpat_d.exp 25> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\unicodedata_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\unicodedata_d.exp 27>_hashlib.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_hashlib_d.pyd 28>------ Rebuild All started: Project: _multiprocessing, Configuration: Debug x64 ------ 28>multiprocessing.c 28>semaphore.c 26>pyexpat.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\pyexpat_d.pyd 25>unicodedata.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\unicodedata_d.pyd 29>------ Rebuild All started: Project: python, Configuration: Debug x64 ------ 30>------ Rebuild All started: Project: _testbuffer, Configuration: Debug x64 ------ 31>------ Rebuild All started: Project: select, Configuration: Debug x64 ------ 30>_testbuffer.c 31>selectmodule.c 29>python.c 30> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_testbuffer_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_testbuffer_d.exp 28> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_multiprocessing_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_multiprocessing_d.exp 31> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\select_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\select_d.exp 28>_multiprocessing.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_multiprocessing_d.pyd 32>------ Rebuild All started: Project: pythonw, Configuration: Debug x64 ------ 31>select.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\select_d.pyd 30>_testbuffer.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_testbuffer_d.pyd 33>------ Rebuild All started: Project: _overlapped, Configuration: Debug x64 ------ 34>------ Rebuild All started: Project: _testembed, Configuration: Debug x64 ------ 32>WinMain.c 33>overlapped.c 34>_testembed.c 29>python.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\python_d.exe 33> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_overlapped_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_overlapped_d.exp 32>pythonw.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\pythonw_d.exe 33>_overlapped.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_overlapped_d.pyd 34>_testembed.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_testembed_d.exe 35>------ Rebuild All started: Project: _testmultiphase, Configuration: Debug x64 ------ 36>------ Rebuild All started: Project: winsound, Configuration: Debug x64 ------ 37>------ Rebuild All started: Project: _testconsole, Configuration: Debug x64 ------ 29>D:\Python\Source\cpython-main\PCbuild\python.vcxproj(130,5): warning MSB3073: The command "setlocal 29>D:\Python\Source\cpython-main\PCbuild\python.vcxproj(130,5): warning MSB3073: set PYTHONPATH=D:\Python\Source\cpython-main\Lib 29>D:\Python\Source\cpython-main\PCbuild\python.vcxproj(130,5): warning MSB3073: "D:\Python\Source\cpython-main\PCbuild\amd64\python_d.exe" "D:\Python\Source\cpython-main\PC\validate_ucrtbase.py" ucrtbased" exited with code -1073741515. 29>Wrote D:\Python\Source\cpython-main\PCbuild\amd64\LICENSE.txt 29>Done building project "python.vcxproj". 38>------ Rebuild All started: Project: _asyncio, Configuration: Debug x64 ------ 36>winsound.c 35>_testmultiphase.c 37>_testconsole.c 38>_asynciomodule.c 35> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_testmultiphase_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_testmultiphase_d.exp 37> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_testconsole_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_testconsole_d.exp 36> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\winsound_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\winsound_d.exp 35>_testmultiphase.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_testmultiphase_d.pyd 39>------ Rebuild All started: Project: _zoneinfo, Configuration: Debug x64 ------ 38> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_asyncio_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_asyncio_d.exp 37>_testconsole.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_testconsole_d.pyd 39>_zoneinfo.c 40>------ Rebuild All started: Project: _queue, Configuration: Debug x64 ------ 36>winsound.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\winsound_d.pyd 41>------ Rebuild All started: Project: _ctypes_test, Configuration: Debug x64 ------ 40>_queuemodule.c 38>_asyncio.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_asyncio_d.pyd 42>------ Rebuild All started: Project: python_uwp, Configuration: Debug x64 ------ 41>_ctypes_test.c 42>python_uwp.cpp 39> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_zoneinfo_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_zoneinfo_d.exp 40> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_queue_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_queue_d.exp 39>_zoneinfo.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_zoneinfo_d.pyd 43>------ Rebuild All started: Project: pythonw_uwp, Configuration: Debug x64 ------ 40>_queue.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_queue_d.pyd 44>------ Rebuild All started: Project: _uuid, Configuration: Debug x64 ------ 41> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_ctypes_test_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_ctypes_test_d.exp 44>_uuidmodule.c 41>_ctypes_test.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_ctypes_test_d.pyd 45>------ Rebuild All started: Project: _wmi, Configuration: Debug x64 ------ 45>cl : command line warning D9002: ignoring unknown option '/std:c++20' 45>_wmimodule.cpp 44> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_uuid_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_uuid_d.exp 44>_uuid.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_uuid_d.pyd 45> Creating library D:\Python\Source\cpython-main\PCbuild\amd64\_wmi_d.lib and object D:\Python\Source\cpython-main\PCbuild\amd64\_wmi_d.exp 43>python_uwp.cpp 45>_wmi.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\_wmi_d.pyd 45>Done building project "_wmi.vcxproj". 42>python_uwp.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\python_uwp_d.exe 43>pythonw_uwp.vcxproj -> D:\Python\Source\cpython-main\PCbuild\amd64\pythonw_uwp_d.exe ========== Rebuild All: 42 succeeded, 2 failed, 1 skipped ==========** ```
AlexSoft73 commented 1 year ago
Log for build.bat: ``` **D:\Python\Source\cpython-main\PCbuild>build.bat Using ""D:\Python\Source\cpython-main\PCbuild\\..\externals\pythonx86\tools\python.exe"" (from environment) Fetching external libraries... bzip2-1.0.8 already exists, skipping. sqlite-3.38.4.0 already exists, skipping. xz-5.2.5 already exists, skipping. zlib-1.2.12 already exists, skipping. Fetching external binaries... libffi-3.4.3 already exists, skipping. openssl-bin-1.1.1q already exists, skipping. tcltk-8.6.12.1 already exists, skipping. Finished. Using "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\MSBuild.exe" (found in the PATH) Using "D:\Python\Source\cpython-main\PCbuild\\..\externals\pythonx86\tools\python.exe" (from environment) D:\Python\Source\cpython-main\PCbuild>"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\MSBuild.exe" "D:\Python\Source\cpython-main\PCbuild\pcbuild.proj" /t:Build /m /nologo /v:m /clp:summary /p:Configuration=Release /p:Platform=x64 /p:IncludeExternals=true /p:IncludeCTypes=true /p:IncludeSSL=true /p:IncludeTkinter=true /p:UseTestMarker= /p:GIT="C:\Program Files\Git\cmd\git.exe" _freeze_module.vcxproj -> D:\Python\Source\cpython-main\PCbuild\win32\_freeze_module.exe Error processing line 1 of C:\Python\Python311\Lib\site-packages\matplotlib-3.6.0-py3.11-nspkg.pth: EXEC : Fatal Python error : init_import_site: Failed to import the site module [D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj] Python runtime state: initialized Traceback (most recent call last): File "C:\Python\Python311\lib\site.py", line 186, in addpackage exec(line) File "", line 1, in File "C:\Python\Python311\lib\importlib\machinery.py", line 15, in from ._bootstrap_external import NamespaceLoader ImportError: cannot import name 'NamespaceLoader' from 'importlib._bootstrap_external' (C:\Python\Python311\lib\importlib\_bootstrap_external.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python\Python311\lib\site.py", line 616, in main() File "C:\Python\Python311\lib\site.py", line 603, in main known_paths = addsitepackages(known_paths) File "C:\Python\Python311\lib\site.py", line 384, in addsitepackages addsitedir(sitedir, known_paths) File "C:\Python\Python311\lib\site.py", line 226, in addsitedir addpackage(sitedir, name, known_paths) File "C:\Python\Python311\lib\site.py", line 196, in addpackage import traceback File "C:\Python\Python311\lib\traceback.py", line 5, in import linecache File "C:\Python\Python311\lib\linecache.py", line 11, in import tokenize File "C:\Python\Python311\lib\tokenize.py", line 33, in import re File "C:\Python\Python311\lib\re\__init__.py", line 125, in from . import _compiler, _parser File "C:\Python\Python311\lib\re\_compiler.py", line 18, in assert _sre.MAGIC == MAGIC, "SRE module mismatch" AssertionError: SRE module mismatch D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: The command ""D:\Python\Source\cpython-main\PCbuild\\..\externals\pythonx86\tools\python.exe" "D: \Python\Source\cpython-main\Tools\scripts\deepfreeze.py" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\importlib._bootstrap.h:impo rtlib._bootstrap" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\importlib._bootstrap_extern al.h:importlib._bootstrap_external" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\zipimport.h:zipimport" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\abc.h:abc" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\codecs.h:codecs" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\io.h:io" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\_collections_abc.h:_collections_abc" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\_sitebuiltins.h:_sitebuiltins" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\genericpath.h:genericpath" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\ntpath.h:ntpath" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\posixpath.h:posixpath" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\os.h:os" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\site.h:site" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\stat.h:stat" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\importlib.util.h:importlib.util" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\importlib.machinery.h:impor tlib.machinery" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\runpy.h:runpy" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__hello__.h:__hello__" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__phello__.h:__phello__" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__phello__.ham.h:__phello__.ham" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__phello__.ham.eggs.h:__phe llo__.ham.eggs" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__phello__.spam.h:__phello__.spam" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\frozen_only.h:frozen_only" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "-o" "D:\Python\Source\cpython-main\Python\deepfreeze\deepfreeze.c"" exited with code 1. Build FAILED. EXEC : Fatal Python error : init_import_site: Failed to import the site module [D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj] D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: The command ""D:\Python\Source\cpython-main\PCbuild\\..\externals\pythonx86\tools\python.exe" "D: \Python\Source\cpython-main\Tools\scripts\deepfreeze.py" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\importlib._bootstrap.h:impo rtlib._bootstrap" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\importlib._bootstrap_extern al.h:importlib._bootstrap_external" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\zipimport.h:zipimport" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\abc.h:abc" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\codecs.h:codecs" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\io.h:io" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\_collections_abc.h:_collections_abc" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\_sitebuiltins.h:_sitebuiltins" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\genericpath.h:genericpath" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\ntpath.h:ntpath" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\posixpath.h:posixpath" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\os.h:os" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\site.h:site" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\stat.h:stat" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\importlib.util.h:importlib.util" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\importlib.machinery.h:impor tlib.machinery" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\runpy.h:runpy" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__hello__.h:__hello__" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__phello__.h:__phello__" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__phello__.ham.h:__phello__.ham" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__phello__.ham.eggs.h:__phe llo__.ham.eggs" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\__phello__.spam.h:__phello__.spam" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "D:\Python\Source\cpython-main\Python\frozen_modules\frozen_only.h:frozen_only" ^ D:\Python\Source\cpython-main\PCbuild\_freeze_module.vcxproj(398,2): error MSB3073: "-o" "D:\Python\Source\cpython-main\Python\deepfreeze\deepfreeze.c"" exited with code 1. 0 Warning(s) 2 Error(s) Time Elapsed 00:00:05.89 D:\Python\Source\cpython-main\PCbuild>** ```
AlexSoft73 commented 1 year ago

Hi Python team,

I manage to get the project compile in MSVS2019.

Thanks in advance, Alexei

AlexSoft73 commented 1 year ago

Understanding python when embedded.

Please, answer the following question

A module is an isolated python execution unit? Meaning each module has its own set of variables?

thanks in advance Alexei

da-woods commented 1 year ago

A module is an isolated python execution unit? Meaning each module has its own set of variables?

Each module has it's own namespace. However variables might be shared between a module. If module B does from A import x then the variable x is shared between A and B.

AlexSoft73 commented 1 year ago

Yes, I understand the import part, if you import means you can access what you imported, ie:

import moduleA as mA (suposing moduleA insde defines a global variable AA) you can access this way mA.AA

Am I right?

AlexSoft73 commented 1 year ago

Hi da-woods

Do you use python embedded or generate comple applications in Python?

Thanks,

da-woods commented 1 year ago

I've used embedded Python before but it's been a while since I last set it up.

AlexSoft73 commented 1 year ago

Hi Python Team

Thanks is advance to all those that have helped me with my bigining in this forum.

============= Phase -1 Call 24 to cmalloc (requesting 262168 bytes)=================

I know when using python from as an application these memory leaks might have no relevance since the OS will free memory for you upon application is finished. Now when embedding Python we have a different story, especially if we are using Python as child threads of the main application thread.

The reason I am asking is, I am no expert in the internal working of Python, I am just pursuing memory leaks and trying to understand why it is happening to try and solve the problem.

============================================== Offending function _PyObject_GC_New in module module "gcmodule.c"

[python] _PyObject_GC_New(PyTypeObject tp) { size_t presize = _PyType_PreHeaderSize(tp); PyObject op = gc_alloc(_PyObject_SIZE(tp), presize); <---- This object (op) is never released when Py_finalize is called. if (op == NULL) { return NULL; } _PyObject_Init(op, tp); return op; } [/python]

================= Stack trace ===================

python312_d.dll!_PyObject_GC_New(_typeobject tp) Line 2302 C python312_d.dll!new_dict(_dictkeysobject keys, _dictvalues values, __int64 used, int free_values_on_failure) Line 737 C python312_d.dll!PyDict_New() Line 842 C python312_d.dll!PyUnicode_InternInPlace(_object p) Line 14669 C python312_d.dll!_PyUnicode_InitStaticStrings() Line 1433 C python312_d.dll!_PyUnicode_InitGlobalObjects(_is interp) Line 14610 C python312_d.dll!pycore_init_global_objects(_is interp) Line 682 C python312_d.dll!pycore_interp_init(_ts tstate) Line 826 C python312_d.dll!pyinit_config(pyruntimestate runtime, _ts tstate_p, const PyConfig config) Line 898 C python312_d.dll!pyinit_core(pyruntimestate runtime, const PyConfig src_config, _ts tstate_p) Line 1061 C python312_d.dll!Py_InitializeFromConfig(const PyConfig * config) Line 1256 C python312_d.dll!Py_InitializeEx(int install_sigs) Line 1294 C

AlexSoft73 commented 1 year ago

Hi Python team,

In function: static void finalize_modules(PyThreadState *tstate)

finalize_restore_builtins(tstate); --> Why restore if we are Finalizing Python

This won't destroy the builtins

Thanks in advance Alexei

AlexSoft73 commented 1 year ago

The sample code is as simple as

#include <Python.h>
int main(...)
{
 //Step-1
 Py_InitializeEx(0);
 Py_FinalizeEx();
Step-2
 Py_InitializeEx(0);
 Py_FinalizeEx();
Step-2
 Py_InitializeEx(0);
 Py_FinalizeEx();

return 0;
}

You will see how between this steps memory used is increasing. Usually while using the Python interpreter user don't get to see this since when the Python interpreter application calls Py_FinalizeEx(); and then finish, hence the OS frees whatever memory is unreleased

Thanks, Alexei

ncoghlan commented 1 year ago

While the init/finalise cycles in https://github.com/python/cpython/blob/main/Programs/_testembed.c are similar to the given example, one difference is that the embedding tests migrated at some point to using Py_InitializeFromConfig directly rather than continuing to use the Py_InitializeEx compatibility API.

Comparing the two initialisation functions, one discrepancy I see is that _testembed_Py_Initialize (https://github.com/python/cpython/blob/b0f89cb4311b696f875e58f14258ce315be09bce/Programs/_testembed.c#L76) is calling PyConfig_ClearConfig while Py_InitializeEx (https://github.com/python/cpython/blob/4e4bfffe2ded7339663945ad4c494db0e88ec96c/Python/pylifecycle.c#L1274) never clears its local config struct.

That doesn't seem right given the PyConfig docs say "When done, the PyConfig_Clear() function must be used to release the configuration memory."

AlexSoft73 commented 1 year ago

Thanks a lot ncoghlan for your reply,

What I can see is that using this initialization method might do what need. One Caveat is: this function is not part of the Python ABI Function set, meaning this, I might lose compatibility among Python versions.

See, I really have concerns with compatibility, in fact I don't do early binding with Python libraries, I use late binding for 2 main reasons: 1- The application might not use Python at all in some circumstances, hence why load python stuff. 2- Let the user update python (as long as ABI set remains promised) and still be able to use Python without recompile the host application.

Again, thanks

AlexSoft73 commented 1 year ago

Hi ncoghlan

Please, can you show me where are the instruction to format what i write, let's say c/c++ code or python code...

thanks

ncoghlan commented 1 year ago

@AlexSoft73 As in you'd like to see if using Py_InitializeFromConfig instead of Py_InitializeEx eliminates the detected leak? That experiment is a matter of using the code from https://docs.python.org/3/c-api/init_config.html#example but dropping the parts that customise the config away from the defaults:

    // Start Py_InitializeEx replacement...
    PyStatus status;
    PyConfig config;
    PyConfig_InitPythonConfig(&config);

    status = Py_InitializeFromConfig(&config);
    if (PyStatus_Exception(status)) {
        // Do something more graceful than terminating the entire process (which is what `Py_InitializeEx` will do if this fails)
    }
    PyConfig_Clear(&config); // This is the step that appears to be missing from `Py_InitializeEx`
    // End of Py_InitializeEx replacement...

If that change doesn't eliminate the leak you're seeing, then that's useful information as well: it means this isn't the problem, and the issue lies elsewhere (perhaps somewhere Windows specific)

vstinner commented 1 year ago

Now when I embed Python in my application things go perfect, except for memory leaks! As a sample by just issuing the following code leaves memory leaks of around (2Mb): (...)

How do you measure the memory? I'm not used to Windows development. On Linux, I check for lines started with Vm in /proc/pid/status:

$ echo $$
21584
$ grep ^Vm /proc/21584/status
VmPeak:   224772 kB
VmSize:   224772 kB
(....)

About your comment:

============= Phase -1 Call 24 to cmalloc (requesting 262168 bytes)=================
(...)
==============================================
Offending function _PyObject_GC_New in module module "gcmodule.c"
(...)

Where does it come from? Is it the output of a tool?

Or did you write it yourself?

I am actually using Python 3.11 and it is happening. It will be of a tremendous help to see that fixed.

Python 3.11.0 final is not released yet. Which exact version did you test?

vstinner commented 1 year ago

I did a test on Windows. I applied this patch:

diff --git a/Programs/_testembed.c b/Programs/_testembed.c
index e5b138ce84..fa196a3a20 100644
--- a/Programs/_testembed.c
+++ b/Programs/_testembed.c
@@ -158,6 +158,8 @@ PyInit_embedded_ext(void)
 // multiple times.
 static int test_repeated_init_exec(void)
 {
+extern Py_ssize_t _Py_GetAllocatedBlocks(void);
+
     if (main_argc < 3) {
         fprintf(stderr, "usage: %s test_repeated_init_exec CODE\n", PROGRAM);
         exit(1);
@@ -174,6 +176,8 @@ static int test_repeated_init_exec(void)
         if (err) {
             return 1;
         }
+       printf("loop #%i: after Py_Finalize(): #refs=%zd, #blocks=%zd\n",
+               i, _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
     }
     return 0;
 }

Rebuilt Python and ran:

vstinner@WIN C:\victor\python\3.11>PCbuild\amd64\_testembed_d.exe test_repeated_init_exec pass
--- Loop #1 ---
loop #1: after Py_Finalize(): #refs=0, #blocks=0
--- Loop #2 ---
loop #2: after Py_Finalize(): #refs=0, #blocks=0
--- Loop #3 ---
loop #3: after Py_Finalize(): #refs=0, #blocks=0
--- Loop #4 ---
loop #4: after Py_Finalize(): #refs=0, #blocks=0

I tested 3.11 and main branches: I get the same output. There is no leak according to _Py_GetRefTotal() and _Py_GetAllocatedBlocks(): memory allocated with Python memory allocators.

These functions don't account memory allocated in the "raw" memory allocation domain, functions like PyMem_RawMalloc(). For example, the "raw" domain is used by Python startup.

But your stack trace contains _PyObject_GC_New() which uses the "object" memory allocation domain: the PyObject_Malloc() function.

vstinner commented 1 year ago

On Linux, it looks like Py_Initialize()+Py_Finalize() called in a loop leaks...

$ ./Programs/_testembed  test_repeated_init_exec 'import os; os.system(f"grep ^VmRSS /proc/{os.getpid()}/status")'
--- Loop #1 ---
VmRSS:     10136 kB
--- Loop #2 ---
VmRSS:     10564 kB
--- Loop #3 ---
VmRSS:     10624 kB
--- Loop #4 ---
VmRSS:     10680 kB

... but if I change _testembed.c to loop more, in fact, the memory usage is stable (the leak was a false alarm):

diff --git a/Programs/_testembed.c b/Programs/_testembed.c
index d635c5a4ab..fd61a4f26a 100644
--- a/Programs/_testembed.c
+++ b/Programs/_testembed.c
@@ -31,7 +31,7 @@ char **main_argv;
 /* Use path starting with "./" avoids a search along the PATH */
 #define PROGRAM_NAME L"./_testembed"

-#define INIT_LOOPS 4
+#define INIT_LOOPS 40

 // Ignore Py_DEPRECATED() compiler warnings: deprecated functions are
 // tested on purpose here.

Output:

--- Loop #1 ---
VmRSS:      9984 kB
--- Loop #2 ---
VmRSS:     10420 kB
--- Loop #3 ---
VmRSS:     10496 kB
--- Loop #4 ---
VmRSS:     10560 kB
--- Loop #5 ---
VmRSS:     10608 kB
(...)
--- Loop #20 ---
VmRSS:     10712 kB
(...)
--- Loop #37 ---
VmRSS:     10712 kB
--- Loop #38 ---
VmRSS:     10712 kB
--- Loop #39 ---
VmRSS:     10712 kB
--- Loop #40 ---
VmRSS:     10708 kB
vstinner commented 1 year ago

I also ran Valgrind on the main branch:

PYTHONMALLOC=malloc valgrind --leak-check=full --show-leak-kinds=all --log-file=valgrind.log --num-callers=20 ./Programs/_testembed  test_repeated_init_exec 'pass'

Valgrind finds a leak of 1 kB:

==28543== HEAP SUMMARY:
==28543==     in use at exit: 1,056 bytes in 6 blocks
==28543==   total heap usage: 113,234 allocs, 113,228 frees, 15,378,972 bytes allocated
==28543== 
==28543== 68 bytes in 1 blocks are possibly lost in loss record 1 of 6
==28543==    at 0x484586F: malloc (vg_replace_malloc.c:381)
==28543==    by 0x55193B: _PyMem_RawMalloc (obmalloc.c:101)
==28543==    by 0x55449D: _PyMem_DebugRawAlloc (obmalloc.c:2509)
==28543==    by 0x55456E: _PyMem_DebugRawMalloc (obmalloc.c:2542)
==28543==    by 0x552598: PyMem_RawMalloc (obmalloc.c:587)
==28543==    by 0x5527C5: _PyMem_RawWcsdup (obmalloc.c:668)
==28543==    by 0x67D917: _PyPathConfig_UpdateGlobal (pathconfig.c:159)
==28543==    by 0x69035E: interpreter_update_config (pylifecycle.c:476)
==28543==    by 0x6921A6: init_interp_main (pylifecycle.c:1117)
==28543==    by 0x6927C5: pyinit_main (pylifecycle.c:1232)
==28543==    by 0x692973: Py_InitializeFromConfig (pylifecycle.c:1263)
==28543==    by 0x41D9F9: init_from_config_clear (_testembed.c:68)
==28543==    by 0x41DA9E: _testembed_Py_Initialize (_testembed.c:81)
==28543==    by 0x41DC70: test_repeated_init_exec (_testembed.c:173)
==28543==    by 0x421754: main (_testembed.c:2124)
==28543== 
(...)
==28543== 
==28543== LEAK SUMMARY:
==28543==    definitely lost: 0 bytes in 0 blocks
==28543==    indirectly lost: 0 bytes in 0 blocks
==28543==      possibly lost: 1,056 bytes in 6 blocks
==28543==    still reachable: 0 bytes in 0 blocks
==28543==         suppressed: 0 bytes in 0 blocks

But in fact, this "leak" are just global variables (_Py_path_config) initialized once and not cleared explicitly. Py_RunMain() calls pymain_free() and so clear these globals, but Py_Initialize()+Py_Finalize() doesn't.

vstinner commented 1 year ago

On Windows, memory usage of PCbuild\amd64\_testembed_d.exe test_repeated_init_exec pass according to Task Manager, at each iteration:

It doesn't look like a memory leak to me: the memory usage looks stable.

Note: I edited Programs/_testembed.c to have 40 iterations.

ncoghlan commented 1 year ago

@vstinner _testembed.c doesn't call Py_InitializeEx, it calls its own init helper which correctly calls PyConfig_Clear. Py_InitializeEx appears to be missing that expected PyConfig_Clear call, so it may be triggering a leak report that _testembed wouldn't currently pick up.

vstinner commented 1 year ago

Oh, I forgot that I rewrote _testembed_Py_Initialize() to avoid the deprecated Py_Initialize() function :-) The function name is now misleading.

vstinner commented 1 year ago

_testembed_Py_Initialize() calls:

    _PyConfig_InitCompatConfig(&config);
    PyConfig_SetString(config, &config->program_name, L"./_testembed");
    Py_InitializeFromConfig(config);

Py_Initialize() is a thin-wrapper to _PyConfig_InitCompatConfig() + Py_InitializeFromConfig():

void Py_Initialize(void) { Py_InitializeEx(1); }

void
Py_InitializeEx(int install_sigs)
{
    ...
    PyConfig config;
    _PyConfig_InitCompatConfig(&config);
    config.install_signal_handlers = install_sigs;
    status = Py_InitializeFromConfig(&config);
    ...
}
vstinner commented 1 year ago

Just in case, I did another test with Py_Initialize():

diff --git a/Programs/_testembed.c b/Programs/_testembed.c
index d635c5a4ab..90550388a3 100644
--- a/Programs/_testembed.c
+++ b/Programs/_testembed.c
@@ -31,7 +31,7 @@ char **main_argv;
 /* Use path starting with "./" avoids a search along the PATH */
 #define PROGRAM_NAME L"./_testembed"

-#define INIT_LOOPS 4
+#define INIT_LOOPS 40

 // Ignore Py_DEPRECATED() compiler warnings: deprecated functions are
 // tested on purpose here.
@@ -168,13 +168,18 @@ static int test_repeated_init_exec(void)
         fprintf(stderr, "--- Loop #%d ---\n", i);
         fflush(stderr);

-        _testembed_Py_Initialize();
+       Py_SetProgramName(L"./_testembed");
+       Py_Initialize();
         int err = PyRun_SimpleString(code);
         Py_Finalize();
         if (err) {
             return 1;
         }
+
+       printf("press a key to continue\n");
+       getchar();
     }
+
     return 0;
 }

PCbuild\amd64\_testembed_d.exe test_repeated_init_exec pass memory usage in Task Manager:

For me, that's not a leak. For example, if they would be a constant leak of 0.1 MB per iteration, the memory would increase from 2.7 MB to 6.7 MB. But here it's more or less stable, between 3.1 and 3.5 MB.

IMO there is no leak and I suggest to just close the issue.

AlexSoft73 commented 1 year ago

Hi to all and Thanks for the answers, Sorry I am a bit late I was out of my work bench and while I was able to read thru emails this conversation I had no source files, nor test enviroment with me.

The platform where I plan to use python is Windows, I cannot speak for Linux/OS/Unix I am not working currently on those platforms

Now, I forked the Python project and recompiled it using msvs2019 and I made a simple modification to 3 functions in obmalloc.c file:

The functions I mdified were:

-_static void _PyMem_RawMalloc(void Py_UNUSED(ctx), size_t size) (Increment counter) -static void _PyMem_RawCalloc(void Py_UNUSED(ctx), size_t nelem, size_t elsize) (Increment counter) -static void _PyMem_RawFree(void Py_UNUSED(ctx), void ptr) (Decrement counter)

when I finished the application, the counters math should be 0, but the result is 14, this means to me that there were 14 calls to "malloc", "calloc" that never got its counter part "free".

MallocCallocCounter: 1123 FreeCounter:1109

We can close this issue if this is the common desire.

Thanks is n advance Alexei

AlexSoft73 commented 1 year ago

Hi ncoghlan

Do you use Windows or Unix based OS?

Thanks for your time. Alexei

AlexSoft73 commented 1 year ago

Hi vstinner and thanks for your replay

You might not consider a leak going from Loop 1: 2.7 MB to Loop 40: 3.5 MB. I do see a leak there,

Stress up your test and take up to 100000 loops to see about the that number.

Thanks a lot for your time, Alexei

vstinner commented 1 year ago

I close the issue. This is no memory leak. It's not perfect, but it's good enough for now :-) Python 3.11 is way better than Python 3.10 and older versions regarding memory leaks when Python is embedded in an application.

You might not consider a leak going from Loop 1: 2.7 MB to Loop 40: 3.5 MB.

You're right: I don't consider it as a leak. Read again what I wrote. If you have a clear reproducer, please open a new issue.

A clear reproducer would mean that each Py_Initialize+Py_Finalize would leak a fixed amount of memory LEAK bytes, and that repeat it N times would leak LEAK x N bytes. It's not the case here.

when I finished the application, the counters math should be 0, but the result is 14, this means to me that there were 14 calls to "malloc", "calloc" that never got its counter part "free".

See my comment about pymain_free(): right, Py_Finalize() doesn't clear all global variables. There are a few bytes which remain allocated, but that's very small (1 kB), and this memory is not growing at each iteration. If it's already allocated, Python just uses it at the next iteration. It's not perfect, but it's acceptable for now.

If someone can propose a design to release this memory with Py_Initialize+Py_Finalize API, I'm interested.

AlexSoft73 commented 1 year ago

But, if you close the issue how are you going to see it. I thought this exchange was to try and fix/improve Python code.

Thanks any ways,

vstinner commented 1 year ago

If someone has a reproducer as I described, please open a new issue.

If someone has an idea to fix the small leak of 1 kB, please open a new issue.

But the bug described in the issue is not a bug: there is no "leak".

AlexSoft73 commented 1 year ago

Are you tesdting this is Windows or Unix derived system?

Thanks again,

Alexei

vstinner commented 1 year ago

Are you tesdting this is Windows or Unix derived system?

My comments where I wrote "On Windows", "Task Manager", "_testembed.exe", etc. are on Windows.

AlexSoft73 commented 1 year ago

Ok vstinner

if you think python has no leaks specially, the memory allocated for globals which makes the Python dll not thread safe, and still don't believe the email where I detected that there are 14 calls requesting memory which memory is never released, that tells me, you use Python as a standalone application, hence never going to see this issue.

Any ways, thanks Alexei

ncoghlan commented 1 year ago

I'm still investigating this, as https://github.com/python/cpython/commit/6415e2ee4955b1a995c1e75544e2506b03780c3d is a 3.11 specific change that dropped the embedding tests' coverage of Py_InitializeEx. Prior to Python 3.11 a missing PyConfig_Clear call would have been entirely lost in the noise of all of the other process level allocations that Py_Finalize wasn't able to clear up.

While I could just add that apparently missing call (along with a new embedding test to specifically cover the convenience/compatibility APIs) and call it done, I'm first seeing if I can find a diagnostic that can clearly track whether the strings in the config struct (which are allocated with PyMem_RawMalloc) are being cleaned up correctly. (The config struct has 21 wide string fields and 5 lists of wide strings that may or may not be populated based on how the interpreter is being initialised, so a missing PyConfig_Clear could readily account for the 14 missing calls to PyMem_RawFree that @AlexSoft73 is detecting).

The refcount tracking and allocated block tracking don't pick those up since they only cover pymalloc and actual Python objects, so I'll be checking valgrind next. If that still doesn't clearly demonstrate a difference between Py_InitializeFromConfig (with a PyConfig_Clear call) and the Py_Initialize wrapper then I'll also resort to the global raw allocation counter approach)

ncoghlan commented 1 year ago

OK, the valgrind results are identical regardless of whether PyConfig_Clear is called or not, and the reason relates to the way that Py_InitializeEx uses PyConfig: it leaves all the dynamically allocated fields empty, so only the interpreter's runtime config struct gets those populated, the passed in configuration doesn't. Calling PyConfig_Clear anyway is still the more correct thing to do, but omitting it isn't actually going to leak anything if the API client never calls PyConfig_Read or one of the other PyConfig_ APIs that populates a dynamically allocated config field.

There are a handful of unmatched PyMem_RawMalloc calls (related to _Py_path_config as @vstinner noted above), but those don't get repeated (later interpreter instances reuse the previous allocations) so the total memory use doesn't grow over time.

What you do get over repeated invocations is increased memory fragmentation in the overall process, which can result in the kind of memory creep reported here without being a true leak.