# DP: Change the interpreter to build and install python extensions
# DP: built with the python-dbg interpreter with a different name into
# DP: the same path (by appending `_d' to the extension name).

Index: b/Lib/distutils/command/build.py
===================================================================
--- a/Lib/distutils/command/build.py
+++ b/Lib/distutils/command/build.py
@@ -91,7 +91,8 @@ class build(Command):
         # 'lib.<plat>' under the base build directory.  We only use one of
         # them for a given distribution, though --
         if self.build_purelib is None:
-            self.build_purelib = os.path.join(self.build_base, 'lib')
+            self.build_purelib = os.path.join(self.build_base,
+                                              'lib' + plat_specifier)
         if self.build_platlib is None:
             self.build_platlib = os.path.join(self.build_base,
                                               'lib' + plat_specifier)
Index: b/Lib/distutils/sysconfig.py
===================================================================
--- a/Lib/distutils/sysconfig.py
+++ b/Lib/distutils/sysconfig.py
@@ -90,7 +90,7 @@ def get_python_inc(plat_specific=0, pref
                 # Include is located in the srcdir
                 inc_dir = os.path.join(srcdir, "Include")
             return inc_dir
-        return os.path.join(prefix, "include", "python" + get_python_version())
+        return os.path.join(prefix, "include", "python" + get_python_version())+(sys.pydebug and "_d" or "")
     elif os.name == "nt":
         return os.path.join(prefix, "include")
     elif os.name == "os2":
@@ -263,7 +263,7 @@ def get_makefile_filename():
     if python_build:
         return os.path.join(project_base, "Makefile")
     lib_dir = get_python_lib(plat_specific=1, standard_lib=1)
-    return os.path.join(lib_dir, "config", "Makefile")
+    return os.path.join(lib_dir, "config"+(sys.pydebug and "_d" or ""), "Makefile")
 
 
 def parse_config_h(fp, g=None):
Index: b/Lib/sysconfig.py
===================================================================
--- a/Lib/sysconfig.py
+++ b/Lib/sysconfig.py
@@ -338,7 +338,7 @@ def get_makefile_filename():
     """Return the path of the Makefile."""
     if _PYTHON_BUILD:
         return os.path.join(_PROJECT_BASE, "Makefile")
-    return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config", "Makefile")
+    return os.path.join(get_path('platstdlib').replace("/usr/local","/usr",1), "config" + (sys.pydebug and "_d" or ""), "Makefile")
 
 # Issue #22199: retain undocumented private name for compatibility
 _get_makefile_filename = get_makefile_filename
@@ -470,7 +470,7 @@ def get_config_h_filename():
         else:
             inc_dir = _PROJECT_BASE
     else:
-        inc_dir = get_path('platinclude').replace("/usr/local","/usr",1)
+        inc_dir = get_path('platinclude').replace("/usr/local","/usr",1)+(sys.pydebug and "_d" or "")
     return os.path.join(inc_dir, 'pyconfig.h')
 
 def get_scheme_names():
Index: b/Makefile.pre.in
===================================================================
--- a/Makefile.pre.in
+++ b/Makefile.pre.in
@@ -121,8 +121,8 @@ SCRIPTDIR=	$(prefix)/lib
 # Detailed destination directories
 BINLIBDEST=	$(LIBDIR)/python$(VERSION)
 LIBDEST=	$(SCRIPTDIR)/python$(VERSION)
-INCLUDEPY=	$(INCLUDEDIR)/python$(VERSION)
-CONFINCLUDEPY=	$(CONFINCLUDEDIR)/python$(VERSION)
+INCLUDEPY=	$(INCLUDEDIR)/python$(VERSION)$(DEBUG_EXT)
+CONFINCLUDEPY=	$(CONFINCLUDEDIR)/python$(VERSION)$(DEBUG_EXT)
 LIBP=		$(LIBDIR)/python$(VERSION)
 
 # Symbols used for using shared libraries
@@ -136,6 +136,8 @@ DESTSHARED=	$(BINLIBDEST)/lib-dynload
 EXE=		@EXEEXT@
 BUILDEXE=	@BUILDEXEEXT@
 
+DEBUG_EXT=	@DEBUG_EXT@
+
 # Short name and location for Mac OS X Python framework
 UNIVERSALSDK=@UNIVERSALSDK@
 PYTHONFRAMEWORK=	@PYTHONFRAMEWORK@
@@ -545,7 +547,7 @@ $(LIBRARY): $(LIBRARY_OBJS)
 	$(AR) $(ARFLAGS) $@ $(sort $(MODOBJS))
 	$(RANLIB) $@
 
-libpython$(VERSION).so: $(LIBRARY_OBJS)
+libpython$(VERSION)$(DEBUG_EXT).so: $(LIBRARY_OBJS)
 	if test $(INSTSONAME) != $(LDLIBRARY); then \
 		$(BLDSHARED) $(PY_LDFLAGS) $(CCSHARED) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
 		$(LN) -f $(INSTSONAME) $@; \
@@ -1201,8 +1203,8 @@ inclinstall:
 	$(INSTALL_DATA) pyconfig.h $(DESTDIR)$(CONFINCLUDEPY)/pyconfig.h
 
 # Install the library and miscellaneous stuff needed for extending/embedding
-# This goes into $(exec_prefix)
-LIBPL=		$(LIBP)/config
+# This goes into $(exec_prefix)$(DEBUG_EXT)
+LIBPL=		$(LIBP)/config$(DEBUG_EXT)
 
 # pkgconfig directory
 LIBPC=		$(LIBDIR)/pkgconfig
Index: b/Misc/python-config.in
===================================================================
--- a/Misc/python-config.in
+++ b/Misc/python-config.in
@@ -44,7 +44,7 @@ for opt in opt_flags:
         print ' '.join(flags)
 
     elif opt in ('--libs', '--ldflags'):
-        libs = ['-lpython' + pyver]
+        libs = ['-lpython' + pyver + (sys.pydebug and "_d" or "")]
         libs += getvar('LIBS').split()
         libs += getvar('SYSLIBS').split()
         # add the prefix/lib/pythonX.Y/config dir, but only if there is no
Index: b/Python/dynload_shlib.c
===================================================================
--- a/Python/dynload_shlib.c
+++ b/Python/dynload_shlib.c
@@ -46,6 +46,10 @@ const struct filedescr _PyImport_DynLoad
     {"module.exe", "rb", C_EXTENSION},
     {"MODULE.EXE", "rb", C_EXTENSION},
 #else
+#ifdef Py_DEBUG
+    {"_d.so", "rb", C_EXTENSION},
+    {"module_d.so", "rb", C_EXTENSION},
+#endif
     {".so", "rb", C_EXTENSION},
     {"module.so", "rb", C_EXTENSION},
 #endif
Index: b/Python/sysmodule.c
===================================================================
--- a/Python/sysmodule.c
+++ b/Python/sysmodule.c
@@ -1524,6 +1524,12 @@ _PySys_Init(void)
                         PyString_FromString("legacy"));
 #endif
 
+#ifdef Py_DEBUG
+	PyDict_SetItemString(sysdict, "pydebug", Py_True);
+#else
+	PyDict_SetItemString(sysdict, "pydebug", Py_False);
+#endif
+
 #undef SET_SYS_FROM_STRING
     if (PyErr_Occurred())
         return NULL;
Index: b/configure.ac
===================================================================
--- a/configure.ac
+++ b/configure.ac
@@ -777,7 +777,7 @@ AC_SUBST(LIBRARY)
 AC_MSG_CHECKING(LIBRARY)
 if test -z "$LIBRARY"
 then
-	LIBRARY='libpython$(VERSION).a'
+	LIBRARY='libpython$(VERSION)$(DEBUG_EXT).a'
 fi
 AC_MSG_RESULT($LIBRARY)
 
@@ -923,8 +923,8 @@ if test $enable_shared = "yes"; then
 	  INSTSONAME="$LDLIBRARY".$SOVERSION
           ;;
     Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*|OpenBSD*)
-	  LDLIBRARY='libpython$(VERSION).so'
-	  BLDLIBRARY='-L. -lpython$(VERSION)'
+	  LDLIBRARY='libpython$(VERSION)$(DEBUG_EXT).so'
+	  BLDLIBRARY='-L. -lpython$(VERSION)$(DEBUG_EXT)'
 	  RUNSHARED=LD_LIBRARY_PATH=`pwd`${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
 	  case $ac_sys_system in
 	      FreeBSD*)
@@ -1050,6 +1050,12 @@ else AC_MSG_RESULT(no); Py_DEBUG='false'
 fi],
 [AC_MSG_RESULT(no)])
 
+if test "$Py_DEBUG" = 'true'
+then
+	DEBUG_EXT=_d
+fi
+AC_SUBST(DEBUG_EXT)
+
 # XXX Shouldn't the code above that fiddles with BASECFLAGS and OPT be
 # merged with this chunk of code?
 
@@ -2129,7 +2135,7 @@ then
 		esac
 		;;
 	CYGWIN*)   SO=.dll;;
-	*)	   SO=.so;;
+	*)	   SO=$DEBUG_EXT.so;;
 	esac
 else
 	# this might also be a termcap variable, see #610332
Index: b/Lib/distutils/tests/test_build_ext.py
===================================================================
--- a/Lib/distutils/tests/test_build_ext.py
+++ b/Lib/distutils/tests/test_build_ext.py
@@ -295,8 +295,8 @@ class BuildExtTestCase(support.TempdirMa
         finally:
             os.chdir(old_wd)
         self.assertTrue(os.path.exists(so_file))
-        self.assertEqual(os.path.splitext(so_file)[-1],
-                         sysconfig.get_config_var('SO'))
+        so_ext = sysconfig.get_config_var('SO')
+        self.assertEqual(so_file[len(so_file)-len(so_ext):], so_ext)
         so_dir = os.path.dirname(so_file)
         self.assertEqual(so_dir, other_tmp_dir)
         cmd.compiler = None
@@ -304,8 +304,7 @@ class BuildExtTestCase(support.TempdirMa
         cmd.run()
         so_file = cmd.get_outputs()[0]
         self.assertTrue(os.path.exists(so_file))
-        self.assertEqual(os.path.splitext(so_file)[-1],
-                         sysconfig.get_config_var('SO'))
+        self.assertEqual(so_file[len(so_file)-len(so_ext):], so_ext)
         so_dir = os.path.dirname(so_file)
         self.assertEqual(so_dir, cmd.build_lib)
 
Index: b/Lib/distutils/tests/test_build.py
===================================================================
--- a/Lib/distutils/tests/test_build.py
+++ b/Lib/distutils/tests/test_build.py
@@ -20,10 +20,6 @@ class BuildTestCase(support.TempdirManag
         # if not specified, plat_name gets the current platform
         self.assertEqual(cmd.plat_name, get_platform())
 
-        # build_purelib is build + lib
-        wanted = os.path.join(cmd.build_base, 'lib')
-        self.assertEqual(cmd.build_purelib, wanted)
-
         # build_platlib is 'build/lib.platform-x.x[-pydebug]'
         # examples:
         #   build/lib.macosx-10.3-i386-2.7
@@ -34,6 +30,10 @@ class BuildTestCase(support.TempdirManag
         wanted = os.path.join(cmd.build_base, 'lib' + plat_spec)
         self.assertEqual(cmd.build_platlib, wanted)
 
+        # build_purelib is build + lib
+        wanted = os.path.join(cmd.build_base, 'lib' + plat_spec)
+        self.assertEqual(cmd.build_purelib, wanted)
+
         # by default, build_lib = build_purelib
         self.assertEqual(cmd.build_lib, cmd.build_purelib)
 
