From 2b86bfc8428d541427b419fb9b0c9187bad00fea Mon Sep 17 00:00:00 2001
From: Philippe SWARTVAGHER <phil.swart@gmx.fr>
Date: Sat, 29 Mar 2025 19:03:05 +0100
Subject: [PATCH] Fix crash with PYTHONDEVMODE=1
Forwarded: https://gitlab.gnome.org/GNOME/dia/-/merge_requests/137

`PYTHONDEVMODE=1 ./dia` segfaults between splash screen and main window:
```
Debug memory block at address p=0x55ca41354dd0: API '!'
    0 bytes originally requested
    The 7 pad bytes at p-7 are not all FORBIDDENBYTE (0xfd):
        at p-7: 0x00 *** OUCH
        at p-6: 0x00 *** OUCH
        at p-5: 0x00 *** OUCH
        at p-4: 0x00 *** OUCH
        at p-3: 0x00 *** OUCH
        at p-2: 0x00 *** OUCH
        at p-1: 0x00 *** OUCH
    Because memory is corrupted at the start, the count of bytes requested
       may be bogus, and checking the trailing pad bytes may segfault.
    The 8 pad bytes at tail=0x55ca41354dd0 are not all FORBIDDENBYTE (0xfd):
        at tail+0: 0x64 *** OUCH
        at tail+1: 0x00 *** OUCH
        at tail+2: 0x00 *** OUCH
        at tail+3: 0x00 *** OUCH
        at tail+4: 0x69 *** OUCH
        at tail+5: 0x00 *** OUCH
        at tail+6: 0x00 *** OUCH
        at tail+7: 0x00 *** OUCH

Enable tracemalloc to get the memory block allocation traceback

Fatal Python error: _PyMem_DebugRawFree: bad ID: Allocated using API '!', verified using API 'r'
Python runtime state: initialized

Current thread 0x00007faee96adac0 (most recent call first):
  <no Python frame>
zsh: IOT instruction  env PYTHONDEVMODE=1 dia
```

This change mimics more what is done in the documentation
(https://docs.python.org/3/c-api/init_config.html#initialization-with-pyconfig)
and fixes the crash.

Original bug report: https://bugs.debian.org/1101349
---
 plug-ins/python/python.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/plug-ins/python/python.c b/plug-ins/python/python.c
index 236ab7349..bfb921850 100644
--- a/plug-ins/python/python.c
+++ b/plug-ins/python/python.c
@@ -85,7 +85,6 @@ dia_py_plugin_unload (PluginInfo *info)
 PluginInitResult
 dia_plugin_init (PluginInfo *info)
 {
-  wchar_t name[] = L"dia\0";
   char *python_argv[] = { "dia-python", NULL };
   char *startup_file;
   FILE *fp;
@@ -109,8 +108,11 @@ dia_plugin_init (PluginInfo *info)
   PyImport_AppendInittab ("dia", &PyInit_dia);
 
   PyConfig_InitPythonConfig (&config);
-  config.program_name = malloc (sizeof (name));
-  memcpy (config.program_name, &name, sizeof (name));
+
+  status = PyConfig_SetString(&config, &config.program_name, L"dia");
+  if (PyStatus_Exception (status)) {
+      goto failed;
+  }
 
   status = PyConfig_SetBytesArgv (&config, 1, python_argv);
   if (PyStatus_Exception (status)) {
-- 
GitLab

