--- lib-python/3/sysconfig.py.orig	2022-03-28 09:51:49 UTC
+++ lib-python/3/sysconfig.py
@@ -442,7 +442,11 @@ def _generate_posix_vars(args):
         module.build_time_vars = vars
         sys.modules[name] = module
 
+    pypy_wrkdir = os.environ.get("PYPY_WRKDIR")  # this is set by FreeBSD port
+
     pybuilddir = 'build/lib.%s-%s' % (get_platform(), _PY_VERSION_SHORT)
+    if pypy_wrkdir is not None:
+        pybuilddir = os.path.join(pypy_wrkdir, pybuilddir)
     if hasattr(sys, "gettotalrefcount"):
         pybuilddir += '-pydebug'
     os.makedirs(pybuilddir, exist_ok=True)
@@ -455,7 +459,10 @@ def _generate_posix_vars(args):
         pprint.pprint(vars, stream=f)
 
     # Create file used for sys.path fixup -- see Modules/getpath.c
-    with open('pybuilddir.txt', 'w', encoding='ascii') as f:
+    pybuilddir_txt = 'pybuilddir.txt'
+    if pypy_wrkdir is not None:
+        pybuilddir_txt = os.path.join(pypy_wrkdir, pybuilddir_txt)
+    with open(pybuilddir_txt, 'w', encoding='utf8') as f:
         f.write(pybuilddir)
 
 def _init_posix(vars):
