Title: [292109] trunk
Revision
292109
Author
[email protected]
Date
2022-03-30 11:39:39 -0700 (Wed, 30 Mar 2022)

Log Message

[GTK][WPE] generate-bundle: self-contained bundle for the MiniBrowser that can work on any distro
https://bugs.webkit.org/show_bug.cgi?id=237107

Rubber-stamped by Philippe Normand.

Source/WebCore:

No new tests, no change in behaviour.

* platform/network/soup/SoupNetworkSession.cpp:
(WebCore::SoupNetworkSession::SoupNetworkSession): Allow to load the TLS database specified on the
environment variable WEBKIT_TLS_CAFILE_PEM when DEVELOPER_MODE is enabled
* platform/network/soup/SoupVersioning.h:
(soup_session_set_tls_database):

Tools:

This implements in the generate-bundle script the support to generate a bundle self-contained that can work on any distro.
To achieve that the bundle contains all the required system libraries inside the bundle (even the graphics drivers).
It also contains the required system resources: icons (for gtk), fontconfig files and fonts, etc.
A custom dlopenwrap library is also added and preloaded. The purpose of this library is to wrap all dlopen() calls
and rewrite the paths to ensure that only libraries inside the bundle are loaded.

The bundle has been tested to be generated with the flatpak build and executed on a range of very different distributions
with sucess: Fedora, Ubuntu, Debian, Alpine, CentOS (different versions of each)

* Scripts/bundle-binary:
* Scripts/generate-bundle:
* Scripts/webkitpy/binary_bundling/bundle.py:
(BinaryBundler):
(BinaryBundler.__init__):
(BinaryBundler._is_system_dep):
(BinaryBundler.set_use_sys_lib_directory):
(BinaryBundler.copy_and_maybe_strip_patchelf):
(BinaryBundler.destination_dir):
(BinaryBundler.generate_wrapper_script):
(BinaryBundler.copy_and_remove_rpath): Deleted.
* Scripts/webkitpy/binary_bundling/dlopenwrap/Makefile: Added.
* Scripts/webkitpy/binary_bundling/dlopenwrap/README.txt: Added.
* Scripts/webkitpy/binary_bundling/dlopenwrap/dlopenwrap.c: Added.
(dlopen_wrapper_path_join):
(is_dir):
(dlopen_wrapper_recursive_find):
(dlopen_wrapper_get_path_for_file_under_dir):
(dlopen_wrapper_find_library_on_libpath):
(dlopen):
(dlmopen):
(dlerror):
* Scripts/webkitpy/style/checker.py:

Modified Paths

Added Paths

Diff

Modified: trunk/Source/WebCore/ChangeLog (292108 => 292109)


--- trunk/Source/WebCore/ChangeLog	2022-03-30 17:38:41 UTC (rev 292108)
+++ trunk/Source/WebCore/ChangeLog	2022-03-30 18:39:39 UTC (rev 292109)
@@ -1,3 +1,18 @@
+2022-03-30  Carlos Alberto Lopez Perez  <[email protected]>
+
+        [GTK][WPE] generate-bundle: self-contained bundle for the MiniBrowser that can work on any distro
+        https://bugs.webkit.org/show_bug.cgi?id=237107
+
+        Rubber-stamped by Philippe Normand.
+
+        No new tests, no change in behaviour.
+
+        * platform/network/soup/SoupNetworkSession.cpp:
+        (WebCore::SoupNetworkSession::SoupNetworkSession): Allow to load the TLS database specified on the
+        environment variable WEBKIT_TLS_CAFILE_PEM when DEVELOPER_MODE is enabled
+        * platform/network/soup/SoupVersioning.h:
+        (soup_session_set_tls_database):
+
 2022-03-30  Chris Dumez  <[email protected]>
 
         Add HashTranslator for ASCIILiteral for faster lookup in HashMaps / HashSets

Modified: trunk/Source/WebCore/platform/network/soup/SoupNetworkSession.cpp (292108 => 292109)


--- trunk/Source/WebCore/platform/network/soup/SoupNetworkSession.cpp	2022-03-30 17:38:41 UTC (rev 292108)
+++ trunk/Source/WebCore/platform/network/soup/SoupNetworkSession.cpp	2022-03-30 18:39:39 UTC (rev 292109)
@@ -133,6 +133,21 @@
     if (soup_auth_negotiate_supported() && !m_sessionID.isEphemeral())
         soup_session_add_feature_by_type(m_soupSession.get(), SOUP_TYPE_AUTH_NEGOTIATE);
 
+#if ENABLE(DEVELOPER_MODE)
+    // Optionally load a custom path with the TLS CAFile. This is used on the GTK/WPE bundles. See script generate-bundle
+    // Don't enable this outside DEVELOPER_MODE because using a non-default TLS database has surprising undesired effects
+    // on how certificate verification is performed. See https://webkit.org/b/237107#c14 and git commit 82999879b on glib
+    const char* customTLSCAFile = g_getenv("WEBKIT_TLS_CAFILE_PEM");
+    if (customTLSCAFile) {
+        GUniqueOutPtr<GError> error;
+        GRefPtr<GTlsDatabase> customTLSDB = adoptGRef(g_tls_file_database_new(customTLSCAFile, &error.outPtr()));
+        if (error)
+            WTFLogAlways("Failed to load TLS database \"%s\": %s", customTLSCAFile, error->message);
+        else
+            soup_session_set_tls_database(m_soupSession.get(), customTLSDB.get());
+    }
+#endif // ENABLE(DEVELOPER_MODE)
+
     setupLogger();
 }
 

Modified: trunk/Source/WebCore/platform/network/soup/SoupVersioning.h (292108 => 292109)


--- trunk/Source/WebCore/platform/network/soup/SoupVersioning.h	2022-03-30 17:38:41 UTC (rev 292108)
+++ trunk/Source/WebCore/platform/network/soup/SoupVersioning.h	2022-03-30 18:39:39 UTC (rev 292109)
@@ -158,4 +158,11 @@
 {
     g_object_set(session, "accept-language", acceptLanguage, nullptr);
 }
+
+static inline void
+soup_session_set_tls_database(SoupSession *session, GTlsDatabase *tls_database)
+{
+    g_object_set(session, "tls-database", tls_database, NULL);
+}
+
 #endif // USE(SOUP2)

Modified: trunk/Tools/ChangeLog (292108 => 292109)


--- trunk/Tools/ChangeLog	2022-03-30 17:38:41 UTC (rev 292108)
+++ trunk/Tools/ChangeLog	2022-03-30 18:39:39 UTC (rev 292109)
@@ -1,3 +1,43 @@
+2022-03-30  Carlos Alberto Lopez Perez  <[email protected]>
+
+        [GTK][WPE] generate-bundle: self-contained bundle for the MiniBrowser that can work on any distro
+        https://bugs.webkit.org/show_bug.cgi?id=237107
+
+        Rubber-stamped by Philippe Normand.
+
+        This implements in the generate-bundle script the support to generate a bundle self-contained that can work on any distro.
+        To achieve that the bundle contains all the required system libraries inside the bundle (even the graphics drivers).
+        It also contains the required system resources: icons (for gtk), fontconfig files and fonts, etc.
+        A custom dlopenwrap library is also added and preloaded. The purpose of this library is to wrap all dlopen() calls
+        and rewrite the paths to ensure that only libraries inside the bundle are loaded.
+
+        The bundle has been tested to be generated with the flatpak build and executed on a range of very different distributions
+        with sucess: Fedora, Ubuntu, Debian, Alpine, CentOS (different versions of each)
+
+        * Scripts/bundle-binary:
+        * Scripts/generate-bundle:
+        * Scripts/webkitpy/binary_bundling/bundle.py:
+        (BinaryBundler):
+        (BinaryBundler.__init__):
+        (BinaryBundler._is_system_dep):
+        (BinaryBundler.set_use_sys_lib_directory):
+        (BinaryBundler.copy_and_maybe_strip_patchelf):
+        (BinaryBundler.destination_dir):
+        (BinaryBundler.generate_wrapper_script):
+        (BinaryBundler.copy_and_remove_rpath): Deleted.
+        * Scripts/webkitpy/binary_bundling/dlopenwrap/Makefile: Added.
+        * Scripts/webkitpy/binary_bundling/dlopenwrap/README.txt: Added.
+        * Scripts/webkitpy/binary_bundling/dlopenwrap/dlopenwrap.c: Added.
+        (dlopen_wrapper_path_join):
+        (is_dir):
+        (dlopen_wrapper_recursive_find):
+        (dlopen_wrapper_get_path_for_file_under_dir):
+        (dlopen_wrapper_find_library_on_libpath):
+        (dlopen):
+        (dlmopen):
+        (dlerror):
+        * Scripts/webkitpy/style/checker.py:
+
 2022-03-29  Alex Christensen  <[email protected]>
 
         Don't create directories on iOS if we are only using ephemeral storages

Modified: trunk/Tools/Scripts/bundle-binary (292108 => 292109)


--- trunk/Tools/Scripts/bundle-binary	2022-03-30 17:38:41 UTC (rev 292108)
+++ trunk/Tools/Scripts/bundle-binary	2022-03-30 18:39:39 UTC (rev 292109)
@@ -46,11 +46,11 @@
 
     if interpreter is None:
         raise RuntimeError("Could not determine interpreter for binary %s" % object)
-    bundler = BinaryBundler(args.dest_dir, False)
-    bundler.copy_and_remove_rpath(interpreter, type='interpreter')
-    bundler.copy_and_remove_rpath(args.binary, type='bin')
+    bundler = BinaryBundler(args.dest_dir)
+    bundler.copy_and_maybe_strip_patchelf(interpreter, type='interpreter', strip=False, patchelf_removerpath=True, patchelf_nodefaultlib=False)
+    bundler.copy_and_maybe_strip_patchelf(args.binary, type='bin', strip=False, patchelf_removerpath=True, patchelf_nodefaultlib=False)
     for lib in libraries:
-        bundler.copy_and_remove_rpath(lib, type='lib')
+        bundler.copy_and_maybe_strip_patchelf(lib, type='lib', strip=False, patchelf_removerpath=True, patchelf_nodefaultlib=False)
     bundler.generate_wrapper_script(interpreter, os.path.basename(args.binary))
     return 0
 

Modified: trunk/Tools/Scripts/generate-bundle (292108 => 292109)


--- trunk/Tools/Scripts/generate-bundle	2022-03-30 17:38:41 UTC (rev 292108)
+++ trunk/Tools/Scripts/generate-bundle	2022-03-30 18:39:39 UTC (rev 292109)
@@ -21,7 +21,6 @@
 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
 import argparse
 import base64
 import datetime
@@ -87,6 +86,60 @@
 fi
 """
 
+FONT_CONF_FILE = """\
+<?xml version="1.0"?>
+<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
+<fontconfig>
+    <its:rules xmlns:its="http://www.w3.org/2005/11/its" version="1.0">
+        <its:translateRule translate="no" selector="/fontconfig/*[not(self::description)]"/>
+    </its:rules>
+
+    <description>Default configuration file</description>
+
+<!-- Font directory list, relative to XDG_DATA_HOME -->
+    <dir prefix="xdg">fonts/fonts</dir>
+
+<!-- Load system customization files, relative to previous dir -->
+    <include ignore_missing="yes">conf.d</include>
+
+<!-- Font cache directory list, relative to XDG_CACHE_HOME -->
+    <cachedir prefix="xdg">fontconfig</cachedir>
+
+<!-- Include also the system font config if is on the standard dir -->
+    <include ignore_missing="yes">/etc/fonts/fonts.conf</include>
+
+<!-- Accept deprecated 'mono' alias, replacing it with 'monospace' -->
+    <match target="pattern">
+        <test qual="any" name="family">
+            <string>mono</string>
+        </test>
+        <edit name="family" mode="assign" binding="same">
+            <string>monospace</string>
+        </edit>
+    </match>
+
+<!-- Accept alternate 'sans serif' spelling, replacing it with 'sans-serif' -->
+    <match target="pattern">
+        <test qual="any" name="family">
+            <string>sans serif</string>
+        </test>
+        <edit name="family" mode="assign" binding="same">
+            <string>sans-serif</string>
+        </edit>
+    </match>
+
+<!-- Accept deprecated 'sans' alias, replacing it with 'sans-serif' -->
+    <match target="pattern">
+        <test qual="any" name="family">
+            <string>sans</string>
+        </test>
+        <edit name="family" mode="assign" binding="same">
+            <string>sans-serif</string>
+        </edit>
+    </match>
+</fontconfig>
+"""
+
 _log = logging.getLogger(__name__)
 LOG_MESSAGE = 25
 
@@ -138,6 +191,9 @@
         wk_build_path = os.environ['WEBKIT_OUTPUTDIR'] if 'WEBKIT_OUTPUTDIR' in os.environ else \
                         os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'WebKitBuild'))
         self._buildpath = os.path.join(wk_build_path, self._configuration.capitalize())
+        self._dlopenwrap_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'webkitpy', 'binary_bundling', 'dlopenwrap'))
+        if not os.path.isdir(self._dlopenwrap_dir):
+            raise RuntimeError("Can't find the dlopenwrap directory at: %s" % self._dlopenwrap_dir)
 
         default_bundle_name = bundle_type  + '_' + self._platform + '_' + self._configuration + '.' + self._compression_type
         if destination and  os.path.isdir(destination):
@@ -145,7 +201,6 @@
         else:
             self._bundle_file_path = os.path.join(wk_build_path, default_bundle_name)
 
-
     def _create_tempdir(self, basedir = None):
         if basedir is not None:
             if not os.path.isdir(basedir):
@@ -153,7 +208,6 @@
             return tempfile.mkdtemp(prefix=os.path.join(os.path.abspath(basedir), 'tmp'))
         return tempfile.mkdtemp()
 
-
     def _run_cmd_and_get_output(self, command):
         _log.debug("EXEC %s" % command)
         command_process = subprocess.Popen(command,
@@ -170,7 +224,6 @@
                     return line.split('=')[1].strip().strip('"')
         return None
 
-
     def _generate_readme(self):
         _log.info('Generate README.txt file')
         readme_file = os.path.join(self._tmpdir, 'README.txt')
@@ -191,36 +244,47 @@
                 readme_handle.write('  - To ensure all the required libraries are installed execute the script: install-dependencies.sh\n')
                 readme_handle.write('  - You can pass the flag "--autoinstall" to this script to automatically install the dependencies if needed.\n')
             readme_handle.write('\nRun instructions:\n')
-            scripts = "script" if len(self._wrapper_scripts) == 1 else "scripts"
+            scripts = 'script' if len(self._wrapper_scripts) == 1 else 'scripts'
             readme_handle.write('  - Execute the wrapper %s in this directory:\n' % scripts)
             for wrapper_script in self._wrapper_scripts:
                 readme_handle.write('    * %s\n' %wrapper_script)
         return True
 
-
     def _generate_wrapper_script(self, interpreter, binary_to_wrap):
         variables = dict()
         mydir = self._bundler.VAR_MYDIR
-        if os.path.isdir(os.path.join(self._bundler.destination_dir(), 'gio')):
+        lib_dir = os.path.join(self._bundler.destination_dir(), 'lib')
+        syslib_dir = os.path.join(self._bundler.destination_dir(), 'sys/lib')
+        bin_dir = os.path.join(self._bundler.destination_dir(), 'bin')
+        share_dir = os.path.join(self._bundler.destination_dir(), 'sys/share')
+
+        if os.path.isdir(os.path.join(syslib_dir, 'gio')):
             gio_var = 'GIO_MODULE_DIR' if self._syslibs == 'bundle-all' else 'GIO_EXTRA_MODULES'
-            variables[gio_var] = "${%s}/gio" % mydir
-
-        if os.path.isdir(os.path.join(self._bundler.destination_dir(), 'gst')):
+            variables[gio_var] = '${%s}/sys/lib/gio' % mydir
+        if os.path.isdir(os.path.join(syslib_dir, 'gst')):
             gst_var = 'GST_PLUGIN_SYSTEM_PATH_1_0' if self._syslibs == 'bundle-all' else 'GST_PLUGIN_PATH_1_0'
-            variables[gst_var] = "${%s}/gst" % mydir
-            variables['GST_REGISTRY_1_0'] = "${%s}/gst/gstreamer-1.0.registry" % mydir
-        if binary_to_wrap != "jsc":
-            variables['WEBKIT_EXEC_PATH'] = "${%s}/bin" % mydir
-            variables['WEBKIT_INJECTED_BUNDLE_PATH'] = "${%s}/lib" % mydir
-        if self._syslibs == 'bundle-all':
-            if binary_to_wrap != "jsc":
-                for var in ['WEB_PROCESS_CMD_PREFIX',
-                            'PLUGIN_PROCESS_CMD_PREFIX',
-                            'NETWORK_PROCESS_CMD_PREFIX',
-                            'GPU_PROCESS_CMD_PREFIX']:
-                    variables[var] = "${%s}" % self._bundler.VAR_INTERPRETER
-        else:
-            interpreter = None
+            variables[gst_var] = '${%s}/sys/lib/gst' % mydir
+            variables['GST_REGISTRY_1_0'] = '${%s}/sys/lib/gst/gstreamer-1.0.registry' % mydir
+            if os.path.isfile(os.path.join(bin_dir, 'gst-plugin-scanner')):
+                variables['GST_PLUGIN_SCANNER'] = '${%s}/bin/gst-plugin-scanner' % mydir
+            # pipewire spa plugins may be needed by gstreamer-pipewire
+            if os.path.isdir(os.path.join(syslib_dir, 'pipewire')):
+                variables['SPA_PLUGIN_DIR'] = '${%s}/sys/lib/pipewire' % mydir
+        if os.path.isdir(os.path.join(syslib_dir, 'dri')):
+            variables['LIBGL_DRIVERS_PATH'] = '${%s}/sys/lib/dri' % mydir
+        if os.path.isdir(os.path.join(syslib_dir, 'glvnd/egl_vendor.d')):
+            variables['__EGL_VENDOR_LIBRARY_DIRS'] = '${%s}/sys/lib/glvnd/egl_vendor.d' % mydir
+        if os.path.isdir(os.path.join(share_dir)):
+            assert(self._syslibs == 'bundle-all')
+            variables['XDG_DATA_HOME'] = '${%s}/sys/share' % mydir
+            variables['XDG_DATA_DIRS'] = '${%s}/sys/share' % mydir
+        if os.path.isdir(os.path.join(share_dir, 'fonts')):
+            variables['FONTCONFIG_PATH'] = '${%s}/sys/share/fonts/config' % mydir
+        if os.path.isdir(os.path.join(syslib_dir, 'gtk')):
+            variables['GTK_PATH'] = '${%s}/sys/lib/gtk' % mydir
+        if binary_to_wrap != 'jsc':
+            variables['WEBKIT_EXEC_PATH'] = '${%s}/bin' % mydir
+            variables['WEBKIT_INJECTED_BUNDLE_PATH'] = '${%s}/lib' % mydir
         self._bundler.generate_wrapper_script(interpreter, binary_to_wrap, variables)
         self._wrapper_scripts.append(binary_to_wrap)
 
@@ -252,9 +316,18 @@
         if os.path.isdir(self._tmpdir):
             shutil.rmtree(self._tmpdir)
 
+    def _touch_reset_mtime(self):
+        _log.info('Update timestamps (touch)')
+        now = datetime.datetime.now().timestamp()
+        for root, dirs, files in os.walk(self._tmpdir):
+            for name in files:
+                os.utime(os.path.join(root, name), times=(now, now))
+            for name in dirs:
+                os.utime(os.path.join(root, name), times=(now, now))
+
     def create(self):
         self._tmpdir = self._create_tempdir(self._buildpath)
-        self._bundler = BinaryBundler(self._tmpdir, self._should_strip_objects)
+        self._bundler = BinaryBundler(self._tmpdir, self._buildpath)
 
         if os.path.isfile(self._bundle_file_path):
             _log.info('Removing previous bundle %s' % self._bundle_file_path)
@@ -264,6 +337,9 @@
             self._create_bundle(bundle_binary)
         self._generate_readme()
 
+        # Potentially avoids errors related to ZIP not able to store mtimes older than 1980
+        self._touch_reset_mtime()
+
         if self._compression_type == 'zip':
             archiver = ZipArchiver(self._bundle_file_path)
         elif self._compression_type == 'tar.xz':
@@ -277,7 +353,6 @@
         _log.log(LOG_MESSAGE, 'Bundle file created at: %s' % self._bundle_file_path)
         return self._bundle_file_path
 
-
     def _get_webkit_binaries(self):
         webkit_binaries = []
         bin_dir = os.path.join(self._buildpath, 'bin')
@@ -290,12 +365,12 @@
             raise RuntimeError('Could not find required WebKit Process binaries. Check if you are passing the right platform value.')
         return webkit_binaries
 
-
-    def _get_webkit_bundlelib(self):
+    def _get_webkit_lib(self, name):
+        libkeyname = name.lower()
         lib_dir = os.path.join(self._buildpath, 'lib')
         bundle_lib = None
         for entry in os.listdir(lib_dir):
-            if entry.endswith('.so') and 'injectedbundle' in entry.lower() and 'test' not in entry.lower():
+            if entry.endswith('.so') and libkeyname in entry.lower() and 'test' not in entry.lower():
                 assert(bundle_lib == None)
                 bundle_lib = os.path.join(lib_dir, entry)
                 break
@@ -302,7 +377,6 @@
         assert(bundle_lib)
         return bundle_lib
 
-
     def _create_archive(self, archiver):
         _log.info('Create archive')
         with archiver:
@@ -331,42 +405,140 @@
         _log.info('Add dependency on system package [%s]: %s' %(package, object))
         return package
 
-
-    def _get_gio_modules(self):
-        gio_modules = []
-        retcode, stdout, stderr = self._run_cmd_and_get_output(['pkg-config', '--variable=giomoduledir', 'gio-2.0'])
+    def _get_pkg_config_var(self, module, var_name, assert_value=True):
+        retcode, stdout, stderr = self._run_cmd_and_get_output(['pkg-config', '--variable=%s' % var_name, module])
         if retcode != 0:
             raise RuntimeError('The pkg-config command returned status %d' % retcode)
-        gio_module_dir = stdout.strip()
-        if not os.path.isdir(gio_module_dir):
-            raise RuntimeError('The pkg-config entry for giomoduledir is not a directory: %s' % gio_module_dir)
-        for entry in os.listdir(gio_module_dir):
-            if entry.endswith('.so'):
-                gio_modules.append(os.path.join(gio_module_dir, entry))
-        return gio_modules
+        var_value = stdout.strip()
+        if assert_value:
+            if var_name.endswith('dir') and not os.path.isdir(var_value):
+                raise RuntimeError('The pkg-config entry for %s is not a directory: %s' % (var_name, var_value))
+            if len(var_value) == 0:
+                raise RuntimeError('The pkg-config entry for %s has zero lenght' % var_value)
+        return var_value
 
+    def _list_files_directory(self, directory, list_inside_subdirs=False, filter_suffix=None):
+        found_files = []
+        for entry in os.listdir(directory):
+            entry_path = os.path.join(directory, entry)
+            if os.path.isdir(entry_path):
+                if list_inside_subdirs:
+                    found_files.extend(self._list_files_directory(entry_path, list_inside_subdirs, filter_suffix))
+            elif os.path.isfile(entry_path):
+                if filter_suffix is None or entry_path.endswith(filter_suffix):
+                    found_files.append(entry_path)
+        if len(found_files) == 0:
+            raise RunTimeError('Can not find any matching file at directory %s' % directory)
+        return found_files
+
+    def _get_gio_modules(self):
+        gio_module_dir = self._get_pkg_config_var('gio-2.0', 'giomoduledir')
+        return self._list_files_directory(gio_module_dir, filter_suffix='.so')
+
+    def _get_gtk_modules(self, subdir):
+        gtk_lib_dir = self._get_pkg_config_var('gtk+-3.0', 'libdir')
+        gtk_binary_version = self._get_pkg_config_var('gtk+-3.0', 'gtk_binary_version')
+        gtk_module_dir = os.path.join(gtk_lib_dir, 'gtk-3.0', gtk_binary_version, subdir)
+        if not os.path.isdir(gtk_module_dir):
+            raise RuntimeError('Can not find the the gtk module dir %s' % gtk_module_dir)
+        return self._list_files_directory(gtk_module_dir, filter_suffix='.so')
+
     def _get_gstreamer_modules(self):
-        gstreamer_plugins = []
-        retcode, stdout, stderr = self._run_cmd_and_get_output(['pkg-config', '--variable=pluginsdir', 'gstreamer-1.0'])
-        if retcode != 0:
-            raise RuntimeError('The pkg-config command returned status %d' % retcode)
-        gstramer_plugins_dir = stdout.strip()
-        if not os.path.isdir(gstramer_plugins_dir):
-            raise RuntimeError('The pkg-config entry for pluginsdir is not a directory: %s' % gstramer_plugins_dir)
-        for entry in os.listdir(gstramer_plugins_dir):
-            if entry.endswith('.so'):
-                gstreamer_plugins.append(os.path.join(gstramer_plugins_dir, entry))
-        return gstreamer_plugins
+        gstreamer_plugins_dir = self._get_pkg_config_var('gstreamer-1.0', 'pluginsdir')
+        return self._list_files_directory(gstreamer_plugins_dir, filter_suffix='.so')
 
+    def _get_gstreamer_plugin_scanner(self):
+        def plugin_scanner_found(plugin_scanner_path):
+            return (os.path.isfile(plugin_scanner_path) and os.access(plugin_scanner_path, os.X_OK))
 
+        gstreamer_plugin_scanner_dir = gio_module_dir = self._get_pkg_config_var('gstreamer-1.0', 'pluginscannerdir', assert_value=False)
+        gstreamer_plugin_scanner = os.path.join(gstreamer_plugin_scanner_dir, 'gst-plugin-scanner')
+        if not plugin_scanner_found(gstreamer_plugin_scanner):
+            # pluginscannerdir pkg-config variable is available only on recent versions of gst
+            # give it a second chance with some known directories on debian/ubuntu and fedora/centos
+            lib_dir = self._get_pkg_config_var('gstreamer-1.0', 'libdir')
+            plugins_dir = self._get_pkg_config_var('gstreamer-1.0', 'pluginsdir')
+            for gstreamer_plugin_scanner_dir in [ os.path.join(lib_dir, 'gstreamer1.0/gstreamer-1.0'), plugins_dir, '/usr/libexec/gstreamer-1.0']:
+                gstreamer_plugin_scanner = os.path.join(gstreamer_plugin_scanner_dir, 'gst-plugin-scanner')
+                if plugin_scanner_found(gstreamer_plugin_scanner):
+                    break
+        if not plugin_scanner_found(gstreamer_plugin_scanner):
+            raise RuntimeError('Could not find gst-plugin-scanner binary at path "%s".' % gstreamer_plugin_scanner)
+        return gstreamer_plugin_scanner
+
+    def _get_libc_libraries(self):
+        libc_library_names = [ 'libanl', 'libBrokenLocale', 'libc', 'libcrypt', 'libdl', 'libgcc_s', 'libm',
+                               'libmvec', 'libnsl', 'libpthread', 'libresolv', 'librt', 'libthread_db', 'libutil']
+        libc_libraries = []
+        lib_dir = self._get_pkg_config_var('dri', 'libdir')
+        for entry in os.listdir(lib_dir):
+            if any(entry.startswith(l+'.so.') for l in libc_library_names) or (entry.startswith('libnss_') and '.so.' in entry):
+                libc_libraries.append(os.path.join(lib_dir, entry))
+        for libc_library_prefix in libc_library_names:
+            if not any(os.path.basename(l).startswith(libc_library_prefix+'.so.') for l in libc_libraries):
+                raise RuntimeError('Unable to find libc library %s' % libc_library_prefix)
+        if not any(os.path.basename(l).startswith('libnss_') for l in libc_libraries):
+            raise RuntimeError('Unable to find libc libnss_ libraries')
+        return libc_libraries
+
+    def _get_mesa_libraries(self):
+        mesa_library_names = ['libglapi', 'libxcb-glx', 'libGLX', 'libEGL', 'libGL', 'libGLESv2', 'libEGL_mesa', 'libGLX_mesa']
+        mesa_libraries = []
+        lib_dir_dri = self._get_pkg_config_var('dri', 'libdir')
+        # Some versions of the flatpak SDK ships the Mesa libraries into a non-standard path.
+        candidate_lib_dirs = [ lib_dir_dri, os.path.join(lib_dir_dri, 'GL/default/lib') ]
+        for lib_dir in candidate_lib_dirs:
+            if os.path.isdir(lib_dir):
+                for entry in os.listdir(lib_dir):
+                    if any(entry.startswith(l+'.so.') for l in mesa_library_names):
+                        mesa_libraries.append(os.path.join(lib_dir, entry))
+        for mesa_library_prefix in mesa_library_names:
+            if not any(os.path.basename(l).startswith(mesa_library_prefix+'.so.') for l in mesa_libraries):
+                raise RuntimeError('Unable to find mesa library %s' % mesa_library_prefix)
+        return mesa_libraries
+
+    def _get_mesa_dri_drivers(self):
+        dridriver_dir = self._get_pkg_config_var('dri', 'dridriverdir')
+        return self._list_files_directory(dridriver_dir, filter_suffix='.so')
+
+    def _get_gdk_pixbuf_loaders(self):
+        loaders_dir = self._get_pkg_config_var('gdk-pixbuf-2.0', 'gdk_pixbuf_moduledir')
+        return self._list_files_directory(loaders_dir, filter_suffix='.so')
+
+    def _get_gdk_query_loaders_binary(self):
+        gdk_pixbuf_query_loader_value = self._get_pkg_config_var('gdk-pixbuf-2.0', 'gdk_pixbuf_query_loaders')
+        gdk_pixbuf_libdir = self._get_pkg_config_var('gdk-pixbuf-2.0', 'libdir')
+        # Some distros (like Debian) don't ship the binary on the declared path on pkg-config, but inside $libdir/gdk-pixbuf-2.0
+        for gdk_pixbuf_binary  in [ gdk_pixbuf_query_loader_value, os.path.join(gdk_pixbuf_libdir, 'gdk-pixbuf-2.0/gdk-pixbuf-query-loaders') ]:
+            if os.path.isfile(gdk_pixbuf_binary) and os.access(gdk_pixbuf_binary, os.X_OK):
+                return gdk_pixbuf_binary
+        raise RuntimeError('Unable to find a valid path to gdk-pixbuf-query-loaders binary')
+
+    def _get_gtk_query_immodules_binary(self):
+        gtk_libdir = self._get_pkg_config_var('gtk+-3.0', 'libdir')
+        for gtk_dir in [ '/usr/bin', gtk_libdir, os.path.join(gtk_libdir, 'libgtk-3-0'), os.path.join(gtk_libdir, 'gtk-3.0') ]:
+            gtk_immodules_binary = os.path.join(gtk_dir, 'gtk-query-immodules-3.0')
+            if os.path.isfile(gtk_immodules_binary) and os.access(gtk_immodules_binary, os.X_OK):
+                return gtk_immodules_binary
+        raise RuntimeError('Unable to find a valid path to gdk-pixbuf-query-loaders binary')
+
+    def _get_pipewire_spa_basedir_and_plugins(self):
+        spa_plugin_dir = self._get_pkg_config_var('libspa-0.2', 'plugindir', assert_value=False)
+        # Currently the flatpak SDK doesn't declare plugindir (not sure why).. fallback to build it from libdir
+        if not os.path.isdir(spa_plugin_dir):
+            spa_plugin_dir = self._get_pkg_config_var('libspa-0.2', 'libdir')
+            spa_plugin_dir = os.path.join(spa_plugin_dir, 'spa-0.2')
+        pipewire_spa_plugins = self._list_files_directory(spa_plugin_dir, list_inside_subdirs=True, filter_suffix='.so')
+        return spa_plugin_dir, pipewire_spa_plugins
+
     def _add_object_or_get_sysdep(self, object, object_type):
         provided_by_system_package = None
         if self._syslibs == 'bundle-all':
-            self._bundler.copy_and_remove_rpath(object, type=object_type)
+            self._bundler.copy_and_maybe_strip_patchelf(object, type=object_type, strip=self._should_strip_objects, patchelf_removerpath=True, patchelf_nodefaultlib=True)
         else:
             provided_by_system_package = self._get_system_package_name(object)
             if not provided_by_system_package:
-                self._bundler.copy_and_remove_rpath(object, type=object_type)
+                self._bundler.copy_and_maybe_strip_patchelf(object, type=object_type, strip=self._should_strip_objects, patchelf_removerpath=True, patchelf_nodefaultlib=False)
         return provided_by_system_package
 
     def _ensure_wpe_backend_symlink(self):
@@ -382,7 +554,85 @@
                     os.symlink(entry, wpe_backend_soname)
                 os.chdir(previous_dir)
                 break
+        if not os.path.isfile(os.path.join(bundle_lib_dir, wpe_backend_soname)):
+            raise RuntimeError('Unable to create libWPEBackend-fdo-1.0.so symlink')
 
+    def _dlopenwrap_make(self, action=""
+        dlopenwrap_path = os.path.join(self._dlopenwrap_dir, 'dlopenwrap.so')
+        previous_cwd = os.getcwd()
+        os.chdir(self._dlopenwrap_dir)
+        if action == 'build':
+            retcode, stdout, stderr = self._run_cmd_and_get_output(['make'])
+            if (retcode != 0) or (not os.path.isfile(dlopenwrap_path)):
+                raise RuntimeError('Error building dlopenwrap.so: The make command returned %d status with this output: %s %s' % (retcode, stdout, stderr))
+        elif action == 'clean':
+            retcode, stdout, stderr = self._run_cmd_and_get_output(['make', 'clean'])
+            if (retcode != 0) or os.path.isfile(dlopenwrap_path):
+                raise RuntimeError('Error cleaning dlopenwrap.so: The make command returned %d status with this output: %s %s' % (retcode, stdout, stderr))
+        else:
+            raise NotImplementedError('Unknown action %s' % action)
+        os.chdir(previous_cwd)
+        return dlopenwrap_path
+
+    def _discover_egl_mesa_config_file(self):
+        egl_libdir = self._get_pkg_config_var('egl', 'libdir')
+        # Not known way of getting the directory dynamically, assume it is there.
+        icd_egl_mesa_config_candidates = ['/usr/share/glvnd/egl_vendor.d/50_mesa.json',
+                                           os.path.join(egl_libdir, 'GL/glvnd/egl_vendor.d/50_mesa.json'),
+                                           os.path.join(egl_libdir, 'glvnd/egl_vendor.d/50_mesa.json')]
+        for icd_egl_mesa_config_candidate in icd_egl_mesa_config_candidates:
+            if os.path.isfile(icd_egl_mesa_config_candidate):
+                return icd_egl_mesa_config_candidate
+        raise RuntimeError('Could not find mesa EGL ICD config')
+
+    def _get_mesa_egl_icd_driver_path(self, icd_config):
+        with open(icd_config, 'r') as f:
+            json_data = json.load(f)
+        egl_icd_library_name = json_data['ICD']['library_path']
+        if os.path.isabs(egl_icd_library_name):
+            raise NotImplementedError('Path rewritting needs to be implemented to handle ICD config files with abspath')
+        # Some versions of the flatpak SDK ships the EGL ICD library into a non-standard path.
+        egl_libdir = self._get_pkg_config_var('egl', 'libdir')
+        egl_icd_library_found = False
+        egl_icd_library_paths = [os.path.join(egl_libdir, egl_icd_library_name), os.path.join(egl_libdir, 'GL/default/lib', egl_icd_library_name)]
+        for egl_icd_library_path in egl_icd_library_paths:
+            if os.path.isfile(egl_icd_library_path):
+                egl_icd_library_found = True
+                break
+        if not egl_icd_library_found:
+            raise RuntimeError('Unable to find the EGL ICD library %s' % egl_icd_library_path)
+        return egl_icd_library_path
+
+    def _get_total_size_dir(self, directory):
+        size = 0
+        for root, dirs, files in os.walk(directory):
+            for file in files:
+                file_path = os.path.join(root, file)
+                if os.path.isfile(file_path):
+                    size += os.path.getsize(file_path)
+        return size
+
+    def _generate_font_conf(self, data_directory):
+        font_conf_path = os.path.join(data_directory, 'fonts.conf')
+        with open(font_conf_path, 'w') as font_conf_handle:
+            font_conf_handle.write(FONT_CONF_FILE)
+
+    def _generate_tls_cafile(self, data_directory):
+        cafile_path = os.path.join(data_directory, 'bundle-ca-certificates.pem')
+        retcode, stdout, stderr = self._run_cmd_and_get_output(['trust', 'extract', '--format=pem-bundle', cafile_path])
+        # trust fails inside flatpak due to https://gitlab.com/freedesktop-sdk/freedesktop-sdk/-/issues/904
+        # fall-back to trying to manually copy the bundle
+        if (retcode != 0) or (not os.path.isfile(cafile_path)) or (os.path.getsize(cafile_path) < 100):
+            _log.warning('Failed to get system CA bundle with the trust command. Trying to fall-back to manual copy.')
+            if os.path.isfile(cafile_path):
+                os.unlink(cafile_path)
+            for candidate_cafile in ['/etc/ssl/certs/ca-certificates.crt', '/etc/ssl/cert.pem', '/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem']:
+                if os.path.isfile(candidate_cafile):
+                    shutil.copy(candidate_cafile, cafile_path)
+                    break
+        if (not os.path.isfile(cafile_path)) or (os.path.getsize(cafile_path) < 100):
+            raise RuntimeError('Failed to generate or copy the system TLS CAFile with the certificates.')
+
     def _create_bundle(self, bundle_binary):
         main_binary_path = os.path.join(self._buildpath, 'bin', bundle_binary)
         if not os.path.isfile(main_binary_path) or not os.access(main_binary_path, os.X_OK):
@@ -389,48 +639,106 @@
             raise ValueError('Cannot find binary for %s at %s' % (bundle_binary, main_binary_path) )
 
         copied_interpreter = None
+        needs_to_create_wpe_backend_symlink = False
         gio_modules = []
+        gtk_print_modules = []
+        gtk_im_modules = []
         gstreamer_modules = []
+        mesa_dri_drivers = []
+        pipewire_spa_plugins = []
+        gdk_pixbuf_loaders = []
+        egl_icd_mesa_config_file = None
         libraries_checked = set()
         system_packages_needed = set()
+        binaries_to_copy = set()
         objects_to_copy = [ main_binary_path ]
+        # We only want to separate the libraries in lib and sys/lib for MiniBrowser and 'all' bundles
+        self._bundler.set_use_sys_lib_directory('MiniBrowser' in self._bundle_binaries)
         if bundle_binary == 'MiniBrowser':
+            # bunddle WebKit libraries
+            objects_to_copy.extend(self._get_webkit_binaries())
+            objects_to_copy.append(self._get_webkit_lib('InjectedBundle'))
+            if self._platform == 'wpe':
+                objects_to_copy.append(self._get_webkit_lib('InspectorResources'))
+            # Bundle extra system related libraries
             gio_modules = self._get_gio_modules()
+            objects_to_copy.extend(gio_modules)
             gstreamer_modules = self._get_gstreamer_modules()
-            objects_to_copy.extend(self._get_webkit_binaries())
-            objects_to_copy.append(self._get_webkit_bundlelib())
-            objects_to_copy.extend(gio_modules)
             objects_to_copy.extend(gstreamer_modules)
+            if self._syslibs == 'bundle-all':
+                # need to ship a copy of gst pluging scanner
+                objects_to_copy.append(self._get_gstreamer_plugin_scanner())
+                # pipewire spa plugins
+                pipewire_spa_plugin_basedir, pipewire_spa_plugins = self._get_pipewire_spa_basedir_and_plugins()
+                objects_to_copy.extend(pipewire_spa_plugins)
+                # graphics drivers
+                mesa_dri_drivers = self._get_mesa_dri_drivers()
+                objects_to_copy.extend(mesa_dri_drivers)
+                objects_to_copy.extend(self._get_mesa_libraries())
+                egl_icd_mesa_config_file = self._discover_egl_mesa_config_file()
+                objects_to_copy.append(self._get_mesa_egl_icd_driver_path(egl_icd_mesa_config_file))
+                # system extra libraries
+                objects_to_copy.extend(self._get_libc_libraries())
+                # gtk modules
+                if self._platform == 'gtk':
+                    gtk_print_modules = self._get_gtk_modules('printbackends')
+                    objects_to_copy.extend(gtk_print_modules)
+                    gtk_im_modules = self._get_gtk_modules('immodules')
+                    objects_to_copy.extend(gtk_im_modules)
+                    gdk_pixbuf_loaders = self._get_gdk_pixbuf_loaders()
+                    objects_to_copy.extend(gdk_pixbuf_loaders)
+                    objects_to_copy.append(self._get_gdk_query_loaders_binary())
+                    objects_to_copy.append(self._get_gtk_query_immodules_binary())
+                # our dlopenwrap lib
+                objects_to_copy.append(self._dlopenwrap_make('build'))
+
         for object in objects_to_copy:
             system_package = None
             if object in gio_modules:
-                system_package = self._add_object_or_get_sysdep(object, 'gio')
-                if system_package:
-                    system_packages_needed.add(system_package)
+                system_package = self._add_object_or_get_sysdep(object, 'lib/gio')
             elif object in gstreamer_modules:
-                system_package = self._add_object_or_get_sysdep(object, 'gst')
-                if system_package:
-                    system_packages_needed.add(system_package)
-            elif object.endswith('.so'):
-                self._bundler.copy_and_remove_rpath(object, type='lib')
+                system_package = self._add_object_or_get_sysdep(object, 'lib/gst')
+            elif object in gtk_print_modules:
+                system_package = self._add_object_or_get_sysdep(object, 'lib/gtk/printbackends')
+            elif object in gtk_print_modules:
+                system_package = self._add_object_or_get_sysdep(object, 'lib/gtk/printbackends')
+            elif object in gtk_im_modules:
+                system_package = self._add_object_or_get_sysdep(object, 'lib/gtk/immodules')
+            elif object in mesa_dri_drivers:
+                system_package = self._add_object_or_get_sysdep(object, 'lib/dri')
+            elif object in gdk_pixbuf_loaders:
+                system_package = self._add_object_or_get_sysdep(object, 'lib/gdk-pixbuf/loaders')
+            elif object in pipewire_spa_plugins:
+                # This is a level-2 indirect dependency (gstreamer -> gst-pipewire -> pipewire-spa-plugin)
+                # For the case of system_packages we rely on the distro dependencies betwen packages
+                # But the bundle-all case we need a special case because this dep is not automatically detected (dlopen of plugins)
+                if self._syslibs == 'bundle-all':
+                    pipewire_spa_plugin_dest_subdir = object.replace(pipewire_spa_plugin_basedir, '', 1)
+                    pipewire_spa_plugin_dest_subdir = os.path.dirname(pipewire_spa_plugin_dest_subdir.lstrip('/'))
+                    pipewire_spa_plugin_dest_subdir = os.path.join('lib/pipewire', pipewire_spa_plugin_dest_subdir)
+                    self._bundler.copy_and_maybe_strip_patchelf(object, type=pipewire_spa_plugin_dest_subdir, strip=self._should_strip_objects, patchelf_removerpath=True, patchelf_nodefaultlib=True)
+            elif '.so' in object:
+                if 'libwpebackend' in object.lower():
+                    needs_to_create_wpe_backend_symlink = True
+                self._bundler.copy_and_maybe_strip_patchelf(object, type='lib', strip=self._should_strip_objects, patchelf_removerpath=True, patchelf_nodefaultlib=self._syslibs=='bundle-all')
             else:
-                self._bundler.copy_and_remove_rpath(object, type='bin')
+                binaries_to_copy.add(object)
             # There is no need to examine the libraries linked with objects coming from a system package,
             # because system packages already declare dependencies between them.
             # However, if we are running with self._syslibs == 'bundle-all' then system_package will be None,
             # and everything will be examined and bundled as we don't account for system packages in that case.
-            if not system_package:
+            if system_package:
+                system_packages_needed.add(system_package)
+            else:
                 libraries, interpreter = self._shared_object_resolver.get_libs_and_interpreter(object)
                 if interpreter is None:
-                    raise RuntimeError("Could not determine interpreter for binary %s" % object)
+                    raise RuntimeError('Could not determine interpreter for binary %s' % object)
                 if copied_interpreter is None:
                     if self._syslibs == 'bundle-all':
-                        self._bundler.copy_and_remove_rpath(interpreter, type='interpreter')
+                        self._bundler.copy_and_maybe_strip_patchelf(interpreter, type='interpreter', strip=self._should_strip_objects, patchelf_removerpath=self._syslibs=='bundle-all', patchelf_nodefaultlib=self._syslibs=='bundle-all')
                     copied_interpreter = interpreter
                 elif copied_interpreter != interpreter:
                     raise RuntimeError('Detected binaries with different interpreters: %s != %s' %(copied_interpreter, interpreter))
-                # FIXME: for --syslibs=bundle-all we would have to copy the libnss_*so* libraries which are dlopen'ed <https://bugs.debian.org/203014>
-                # Also we should include config files like fontconfig stuff or support files like icons.
                 for library in libraries:
                     if library in libraries_checked:
                         _log.debug('Skip already checked [lib]: %s' % library)
@@ -439,12 +747,102 @@
                     system_package = self._add_object_or_get_sysdep(library, 'lib')
                     if system_package:
                         system_packages_needed.add(system_package)
+                    elif 'libwpebackend' in library.lower():
+                        needs_to_create_wpe_backend_symlink = True
+        if needs_to_create_wpe_backend_symlink:
+            self._ensure_wpe_backend_symlink()
+        for binary in binaries_to_copy:
+            if self._syslibs == 'bundle-all':
+                self._bundler.copy_and_maybe_strip_patchelf(binary, type='bin', strip=self._should_strip_objects, patchelf_removerpath=True, patchelf_nodefaultlib=True, patchelf_setinterpreter_relativepath=interpreter)
+            else:
+                self._bundler.copy_and_maybe_strip_patchelf(binary, type='bin', strip=self._should_strip_objects, patchelf_removerpath=True, patchelf_nodefaultlib=False)
 
-        self._ensure_wpe_backend_symlink()
+        # Now copy data files to share dir (only needed when bunding all for MiniBrowser).
+        # We assume that the system uses standard paths at /usr/share and /etc for this resources
+        # Every path should be checked and if some one is not found, then it will raise an error.
+        if bundle_binary == 'MiniBrowser' and self._syslibs == 'bundle-all':
+            target_share_dir = os.path.join(self._tmpdir, 'sys/share')
+            # Copy glvnd EGL json files
+            _log.info('Copy EGL config files')
+            egl_icd_configdir_dest = os.path.join(self._tmpdir, 'sys/lib/glvnd/egl_vendor.d')
+            if not os.path.isdir(egl_icd_configdir_dest):
+                os.makedirs(egl_icd_configdir_dest)
+                shutil.copy(egl_icd_mesa_config_file, egl_icd_configdir_dest)
+            # Copy glib-2 compiled schemas
+            _log.info('Copy Glib compiled schemas')
+            schemas_target_dir = os.path.join(target_share_dir, 'glib-2.0/schemas')
+            os.makedirs(schemas_target_dir)
+            compiled_schemas_file = '/usr/share/glib-2.0/schemas/gschemas.compiled'
+            if not os.path.isfile(compiled_schemas_file):
+                raise NotImplementedError("Can't find the gschemas.compiled file at the standard location in this system")
+            shutil.copy(compiled_schemas_file, schemas_target_dir)
+            _log.info('Copy shared mime info cache')
+            # Same for shared-mime-info cache
+            mime_target_dir = os.path.join(target_share_dir, 'mime')
+            os.makedirs(mime_target_dir)
+            mime_cache = '/usr/share/mime/mime.cache'
+            if not os.path.isfile(mime_cache):
+                raise NotImplementedError("Can't find the mime.cache file from shared-mime-info at the standard location in this system")
+            shutil.copy(mime_cache, mime_target_dir)
+            _log.info('Generate fontconfig config')
+            # Fontconfig fonts and config
+            target_font_config_dir = os.path.join(target_share_dir, 'fonts/config')
+            target_font_data_dir = os.path.join(target_share_dir, 'fonts/fonts')
+            os.makedirs(target_font_config_dir)
+            # We keep assuming standard locations for this files on the target system
+            system_font_config_dir = '/etc/fonts/conf.d'
+            system_font_data_dir = '/usr/share/fonts'
+            if not (os.path.isdir(system_font_config_dir) and os.path.isdir(system_font_data_dir)):
+                raise NotImplementedError("Can't find the fontconfig files at the standard location in this system")
+            shutil.copytree(system_font_config_dir, os.path.join(target_font_config_dir, os.path.basename(system_font_config_dir)))
+            self._generate_font_conf(target_font_config_dir)
+            _log.info('Copy fonts')
+            # We copy every font, so this may copy lot of data if you have lot of fonts installed.
+            # So print a warning in that ase
+            system_font_data_size = self._get_total_size_dir(system_font_data_dir)
+            if system_font_data_size > 104857600:  # 100 MB
+                _log.warning('Copying %d MB of font data from the system at /usr/share/fonts. This should be optimized.' % int(system_font_data_size / (1024*1024)))
+            shutil.copytree(system_font_data_dir, target_font_data_dir)
+            # Copy XKB data
+            _log.info('Copy XKB data')
+            system_xkb_data = '/usr/share/X11/xkb'
+            if not (os.path.isdir(system_xkb_data)):
+                raise NotImplementedError("Can't find the XKB data files at the standard location in this system")
+            target_xkb_data = os.path.join(target_share_dir, 'xkb')
+            shutil.copytree(system_xkb_data, target_xkb_data)
+            # Flatpak configures gnutls to use the p11-kit trust store and then uses p11-kit to access the host SSL certificates.
+            # - It starts a p11 kit server on the hosts and bind-mounting a socket that later is used from inside the sandbox via p11-kit-client.so
+            # See: https://github.com/p11-glue/p11-kit/issues/68
+            # Starting a p11-kit server is problematic for the use case of the bundle, and also will only work if the host is configured to use p11-kit
+            # So we take a different approach here.
+            # 1. We generate a bundle-ca-certificates.pem file with all the certs of the system were the bundle was generated and we ship this file
+            # 2. At runtime we look for the system TLS ca-bundle.pem file and we use it. If we can't find it then we default to using the one shipped inside the bundle.
+            # We pass the path to the TLS ca-bundle.pem file using the env var WEBKIT_TLS_CAFILE_PEM
+            # The host p11-kit setup may still work if it is using the same paths for loading the p11-kit modules, but otherwise it will fail to load the modules.
+            # That is ok, since we don't need anymore a working p11-kit setup. If it works it will be used, but if not we have a fallback.
+            # To debug this is useful to export P11_KIT_DEBUG=all
+            # This approach also allows this bundle script go generate a working bundle when gnutls is not configured to use p11-kit.
+            _log.info('Generate TLS CA certificates file')
+            certs_target_dir = os.path.join(target_share_dir, 'certs')
+            os.makedirs(certs_target_dir)
+            self._generate_tls_cafile(certs_target_dir)
+            if self._platform == 'gtk':
+                _log.info('Copy basic GTK icons and themes.')
+                icons_target_dir = os.path.join(target_share_dir, 'icons')
+                os.makedirs(icons_target_dir)
+                for gtk_icon_dir in ['/usr/share/icons/Adwaita', '/usr/share/icons/hicolor']:
+                    if not os.path.isdir(gtk_icon_dir):
+                        raise NotImplementedError('Can not find the GTK icon theme at path "%s" in this system' % gtk_icon_dir)
+                    shutil.copytree(gtk_icon_dir, os.path.join(icons_target_dir, os.path.basename(gtk_icon_dir)))
+
+        # Finally generate the wrappers.
         self._generate_wrapper_script(interpreter, bundle_binary)
-        if bundle_binary == "MiniBrowser":
+        if bundle_binary == 'MiniBrowser':
             self._generate_wrapper_script(interpreter, self._port_binary_preffix + 'WebDriver')
         self._generate_install_deps_script(system_packages_needed)
+        # Clean remaining stuff
+        if bundle_binary == 'MiniBrowser' and self._syslibs == 'bundle-all':
+            self._dlopenwrap_make('clean')
 
 
 class BundleUploader(object):

Modified: trunk/Tools/Scripts/webkitpy/binary_bundling/bundle.py (292108 => 292109)


--- trunk/Tools/Scripts/webkitpy/binary_bundling/bundle.py	2022-03-30 17:38:41 UTC (rev 292108)
+++ trunk/Tools/Scripts/webkitpy/binary_bundling/bundle.py	2022-03-30 18:39:39 UTC (rev 292109)
@@ -31,68 +31,193 @@
 
 class BinaryBundler:
     VAR_MYDIR = 'MYDIR'
-    VAR_INTERPRETER = 'INTERPRETER'
 
-    def __init__(self, destination_dir, should_strip_objects):
-        if shutil.which('patchelf') is None:
-            _log.error("Could not find `patchelf` in $PATH")
-            raise Exception("Missing required binary `patchelf`")
+    def __init__(self, destination_dir, build_path=None):
         self._destination_dir = destination_dir
-        self._should_strip_objects = should_strip_objects
+        self._has_patched_interpreter_relpath = False
+        self._build_path = build_path
+        self._should_use_sys_lib_directory = False
 
-    def destination_dir(self):
-        return self._destination_dir
+    def _is_system_dep(self, path):
+        if self._build_path is not None:
+            # We don't consider libwpe and libWPEBackend-fdo syslibs (even when those are not built directly). Neither dlopenwrap
+            if any(p in path.lower() for p in ['libwpe', 'dlopenwrap']):
+                return False
+            return not path.startswith(self._build_path)
+        return False
 
-    def copy_and_remove_rpath(self, orig_file, type='bin', destination_dir=None):
+    def set_use_sys_lib_directory(self, should_use_sys_lib_directory):
+        self._should_use_sys_lib_directory = should_use_sys_lib_directory
+
+    def copy_and_maybe_strip_patchelf(self, orig_file, type='bin', strip=True, patchelf_removerpath=True, patchelf_nodefaultlib=False, patchelf_setinterpreter_relativepath=None, object_final_destination_dir=None):
+        """ This does the following:
+            1. Copies the binary/lib (object)
+            2. Optionally runs patchelf with different parameters
+            3. Optionally strips the binary
+            If the file is a symlink pointing another file then the symlink is preserved (copying the file pointed)
+        """
+
         dir_suffix = 'lib' if type == 'interpreter' else type
-        destination_dir = os.path.join(self._destination_dir, dir_suffix)
-        if not os.path.isdir(destination_dir):
-            os.makedirs(destination_dir)
+        if object_final_destination_dir is None:
+            object_final_destination_dir = self._destination_dir
+            # If set_use_sys_lib_directory() is enabled then system libraries are shipped in $ROOT/sys/lib to allow to redistribute them separately.
+            # However, the interpreter is always shipped in $ROOT/lib and all the binaries are always shipped in $ROOT/bin
+            # Even when they are system_deps because of patchelf_setinterpreter_relativepath
+            if self._should_use_sys_lib_directory and self._is_system_dep(orig_file) and type not in ['interpreter', 'bin']:
+                object_final_destination_dir = os.path.join(object_final_destination_dir, 'sys')
+            object_final_destination_dir = os.path.join(object_final_destination_dir, dir_suffix)
+        if not os.path.isdir(object_final_destination_dir):
+            os.makedirs(object_final_destination_dir)
 
         if not os.path.isfile(orig_file):
             raise ValueError('Can not find file %s' % orig_file)
 
         _log.info('Add to bundle [%s]: %s' % (type, orig_file))
+
+        # Preserve symlinks and copy the targets
+        if os.path.islink(orig_file):
+            symlink_src_file = os.path.realpath(orig_file)
+            symlink_src_basename = os.path.basename(symlink_src_file)
+            symlink_dst_basename = os.path.basename(orig_file)
+            symlink_dst_fullpath = os.path.join(object_final_destination_dir, symlink_dst_basename)
+            if symlink_src_basename != symlink_dst_basename:
+                try:
+                    # symlink_dst_fullpath -> symlink_src_basename
+                    os.symlink(symlink_src_basename, symlink_dst_fullpath)
+                except FileExistsError:
+                    previous_symlink_src_path = os.path.realpath(symlink_dst_fullpath)
+                    previous_symlink_src_basename = os.path.basename(previous_symlink_src_path)
+                    if previous_symlink_src_basename != symlink_src_basename:
+                        raise RuntimeError('Not overwriting previous symlink %s pointing to %s with a symlink pointing to %s' % (symlink_dst_fullpath, previous_symlink_src_basename, symlink_src_basename))
+                return self.copy_and_maybe_strip_patchelf(symlink_src_file, type, strip, patchelf_removerpath, patchelf_nodefaultlib, patchelf_setinterpreter_relativepath, object_final_destination_dir)
+
         try:
-            shutil.copy(orig_file, destination_dir)
+            shutil.copy(orig_file, object_final_destination_dir)
         except shutil.SameFileError:
             # May reasonably happen if the caller tries to bundle the files 'in place'.
             pass
 
-        patch_elf_command = ['patchelf', '--remove-rpath', os.path.join(destination_dir, os.path.basename(orig_file))]
-        if subprocess.call(patch_elf_command) != 0:
-            _log.error('The patchelf command returned non-zero status')
+        if type == 'interpreter':
+            return  # no strip/patchelf over it
 
-        if self._should_strip_objects:
-            if shutil.which('strip'):
-                strip_command = ['strip', '--strip-unneeded', os.path.join(destination_dir, os.path.basename(orig_file))]
-                if subprocess.call(strip_command) != 0:
-                    _log.error('The strip command returned non-zero status')
-            else:
-                _log.warning('strip not found. Not stripping object')
+        # Running 'strip' after 'patchelf' may corrupt binaries, so run first 'strip'.
+        # See: https://github.com/NixOS/patchelf/issues/371
+        if strip:
+            if not shutil.which('strip'):
+                _log.warning('Unable to find the strip command in the system. Please install it.')
+                raise Exception('Missing required program "strip"')
+            strip_command = ['strip', '--strip-unneeded', os.path.join(object_final_destination_dir, os.path.basename(orig_file))]
+            if subprocess.call(strip_command) != 0:
+                _log.error('The strip command returned non-zero status')
 
+        patchelf_arguments = []
+        if patchelf_removerpath:
+            patchelf_arguments.append("--remove-rpath")
+        if type == 'bin':
+            if patchelf_nodefaultlib:
+                patchelf_arguments.append("--no-default-lib")
+            if patchelf_setinterpreter_relativepath:
+                previous_cwd = os.getcwd()
+                os.chdir(self.destination_dir())
+                # We only want the basename of the interpreter because we are updating it
+                # to use a relative path inside lib/ (which is were we copied it previously)
+                new_interpreter_relpath = os.path.join('lib', os.path.basename(patchelf_setinterpreter_relativepath))
+                if not os.path.isfile(new_interpreter_relpath):
+                    raise ValueError('Unable to find interpreter %s at directory %s' % (new_interpreter, self.destination_dir()))
+                patchelf_arguments.extend(['--set-interpreter', new_interpreter_relpath])
+                self._has_patched_interpreter_relpath = True
+        if patchelf_arguments:
+            # If we have resolved patchelf_arguments then we should run patchelf
+            patchelf_arguments.append(os.path.join(object_final_destination_dir, os.path.basename(orig_file)))
+            if not shutil.which('patchelf'):
+                raise RuntimeError('Unable to find the "patchelf" command in the system. Please install it.')
+            if subprocess.call(['patchelf'] + patchelf_arguments) != 0:
+                raise RuntimeError('The "patchelf" command with arguments "%s" returned non-zero status' % ' '.join(patchelf_arguments))
+
+            if patchelf_setinterpreter_relativepath:
+                os.chdir(previous_cwd)
+
+    def destination_dir(self):
+        return self._destination_dir
+
     def generate_wrapper_script(self, interpreter, binary_to_wrap, extra_environment_variables={}):
         if not os.path.isfile(os.path.join(self._destination_dir, 'bin', binary_to_wrap)):
             raise RuntimeError('Cannot find binary to wrap for %s' % binary_to_wrap)
         _log.info('Generate wrapper script %s' % binary_to_wrap)
         script_file = os.path.join(self._destination_dir, binary_to_wrap)
+        lib_dir = os.path.join(self._destination_dir, 'lib')
+        syslib_dir = os.path.join(self._destination_dir, 'sys/lib')
+        bin_dir = os.path.join(self._destination_dir, 'bin')
+        share_dir = os.path.join(self._destination_dir, 'sys/share')
 
         with open(script_file, 'w') as script_handle:
             script_handle.write('#!/bin/sh\n')
             script_handle.write('%s="$(dirname $(readlink -f $0))"\n' % self.VAR_MYDIR)
-            script_handle.write('export LD_LIBRARY_PATH="${%s}/lib"\n' % self.VAR_MYDIR)
 
-            if interpreter is not None:
-                script_handle.write('INTERPRETER="${%s}/lib/%s"\n' % (self.VAR_MYDIR, os.path.basename(interpreter)))
+            if self._has_patched_interpreter_relpath:
+                # The interprerter (section PT_INTERP in ELF binary) needs to be a pre-defined path
+                # So the only way of using our interpreter in an unknown destination dir is to use relative paths
+                # For relative paths to work, we need to CD into the main basedir, but doing that may break
+                # any parameter the user has passed as a relative path to where she is working (like a relpath to some html file)
+                # So we try to update the arguments resolving relative paths to absolute before executing the program
+                # Trick to update the arguments inspired from https://unix.stackexchange.com/a/421160
+                script_handle.write('# Shipped binaries have a relpath to the interpreter, so update passed args with fullpaths and cd to ${MYDIR}\n')
+                script_handle.write('args_update_relpaths_to_abs() {\n')
+                script_handle.write('    for arg in "$@"; do\n')
+                script_handle.write('      [ -e "${arg}" -a "${arg}" != "${a#/}" ] && arg="$(readlink -f "${arg}")"\n')
+                script_handle.write('      printf %s "${arg}" | sed "s/\'/\'\\\\\\\\\'\'/g;1s/^/\'/;\\$s/\\$/\' /"\n')
+                script_handle.write('    done\n')
+                script_handle.write('echo " "\n')
+                script_handle.write('}\n')
+                script_handle.write('eval "set -- "$(args_update_relpaths_to_abs "$@")""\n')
+                script_handle.write('cd "${MYDIR}"\n')
 
-            # May use the value of INTERPRETER, so has to come after
-            # the definition.
+            if os.path.isfile(os.path.join(share_dir, 'certs/bundle-ca-certificates.pem')):
+                script_handle.write('# Try to use the system CA file if possible, otherwise use the bundled one\n')
+                script_handle.write('for WEBKIT_TLS_CAFILE_PEM in /etc/ssl/certs/ca-certificates.crt /etc/ssl/cert.pem /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem "${MYDIR}/sys/share/certs/bundle-ca-certificates.pem"; do\n')
+                script_handle.write('    [ -f "${WEBKIT_TLS_CAFILE_PEM}" ] && grep -q "BEGIN CERTIFICATE" "${WEBKIT_TLS_CAFILE_PEM}" && export WEBKIT_TLS_CAFILE_PEM && break\n')
+                script_handle.write('done\n')
+
             for var, value in extra_environment_variables.items():
-                script_handle.write('export %s=\"%s\"\n' % (var, value))
+                script_handle.write('export %s="%s"\n' % (var, value))
 
-            if interpreter is not None:
+            if os.path.isdir(syslib_dir):
+                # Preffer to use the system XKB data files, but if they are not on the expected location use our own.
+                xkb_bundled = False
+                for entry in os.listdir(syslib_dir):
+                    if entry.startswith('libxkbcommon.so'):
+                        xkb_bundled = True
+                        break
+                if xkb_bundled:
+                    assert os.path.isdir(os.path.join(share_dir, 'xkb'))
+                    script_handle.write('[ -d /usr/share/X11/xkb ] || export XKB_CONFIG_ROOT="${%s}/sys/share/xkb"\n' % self.VAR_MYDIR)
+
+            ld_library_path = '${%s}/lib' % self.VAR_MYDIR
+            if os.path.isdir(syslib_dir):
+                ld_library_path += ':${%s}/sys/lib' % self.VAR_MYDIR
+
+            # Update cache of gdk-pixbuf loaders if needed (first run or when the absolute paths on disk have changed).
+            if os.path.isdir(os.path.join(syslib_dir, 'gdk-pixbuf/loaders')):
+                script_handle.write('export GDK_PIXBUF_MODULEDIR="${%s}/sys/lib/gdk-pixbuf/loaders"\n' % self.VAR_MYDIR)
+                script_handle.write('export GDK_PIXBUF_MODULE_FILE="${%s}/sys/lib/gdk-pixbuf/loaders.cache"\n' % self.VAR_MYDIR)
+                script_handle.write('grep -sq "\\"${GDK_PIXBUF_MODULEDIR}/" "${GDK_PIXBUF_MODULE_FILE}" || LD_LIBRARY_PATH="%s" "${%s}/bin/gdk-pixbuf-query-loaders" --update-cache\n' % (ld_library_path, self.VAR_MYDIR))
+
+            # Same for gtk immodules cache
+            if os.path.isdir(os.path.join(syslib_dir, 'gtk/immodules')):
+                script_handle.write('export GTK_IM_MODULE_DIR="${%s}/sys/lib/gtk/immodules"\n' % self.VAR_MYDIR)
+                script_handle.write('export GTK_IM_MODULE_FILE="${%s}/sys/lib/gtk/immodules/immodules.cache"\n' % self.VAR_MYDIR)
+                script_handle.write('grep -sq "\\"${GTK_IM_MODULE_DIR}/" "${GTK_IM_MODULE_FILE}" || LD_LIBRARY_PATH="%s" "${%s}/bin/gtk-query-immodules-3.0" --update-cache "${GTK_IM_MODULE_DIR}"/*.so\n' % (ld_library_path, self.VAR_MYDIR))
+
+            # LD_LIBRARY_PATH is set at the end, just before the exec() call and before calling programs bundled, otherwise it may break commands from the system like script's usage of sed/readlink/grep
+            script_handle.write('export LD_LIBRARY_PATH="%s"\n' % ld_library_path)
+            dlopenwrap_libname = 'dlopenwrap.so'
+            if os.path.isfile(os.path.join(lib_dir, dlopenwrap_libname)):
+                script_handle.write('export LD_PRELOAD="${%s}/lib/%s"\n' % (self.VAR_MYDIR, dlopenwrap_libname))
+            # If we have patched the binaries to use a relative relpath then load the binary directly without prefixing it with the interpreter (it allows the process to use the correct progname)
+            if self._has_patched_interpreter_relpath:
+                script_handle.write('exec "${%s}/bin/%s" "$@"\n' % (self.VAR_MYDIR, binary_to_wrap))
+            else:
+                script_handle.write('INTERPRETER="${%s}/lib/%s"\n' % (self.VAR_MYDIR, os.path.basename(interpreter)))
                 script_handle.write('exec "${INTERPRETER}" "${%s}/bin/%s" "$@"\n' % (self.VAR_MYDIR, binary_to_wrap))
-            else:
-                script_handle.write('exec "${%s}/bin/%s" "$@"\n' % (self.VAR_MYDIR, binary_to_wrap))
 
         os.chmod(script_file, 0o755)

Added: trunk/Tools/Scripts/webkitpy/binary_bundling/dlopenwrap/Makefile (0 => 292109)


--- trunk/Tools/Scripts/webkitpy/binary_bundling/dlopenwrap/Makefile	                        (rev 0)
+++ trunk/Tools/Scripts/webkitpy/binary_bundling/dlopenwrap/Makefile	2022-03-30 18:39:39 UTC (rev 292109)
@@ -0,0 +1,16 @@
+THIS_DIR := $(strip $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))))
+CC = gcc
+CFLAGS = -fPIC -Wall -Wextra -O2
+LDFLAGS = -nostartfiles -shared -ldl
+RM = rm -f
+TARGET_LIB = dlopenwrap.so
+SRCS = $(THIS_DIR)/dlopenwrap.c
+
+all: ${TARGET_LIB}
+
+$(TARGET_LIB): $(SRCS)
+	$(CC) $(CFLAGS) $(LDFLAGS) -Wl,-soname,$@ -o $@ $^
+
+.PHONY: clean
+clean:
+	-${RM} ${TARGET_LIB}

Added: trunk/Tools/Scripts/webkitpy/binary_bundling/dlopenwrap/README.txt (0 => 292109)


--- trunk/Tools/Scripts/webkitpy/binary_bundling/dlopenwrap/README.txt	                        (rev 0)
+++ trunk/Tools/Scripts/webkitpy/binary_bundling/dlopenwrap/README.txt	2022-03-30 18:39:39 UTC (rev 292109)
@@ -0,0 +1,9 @@
+This is a shared library to wrap dlopen() and dlmopen() function calls
+and rewrite the paths loaded to ensure that the library loaded is inside
+LD_LIBRARY_PATH environment variables.
+
+It is used by the script generate-bundle that builds this library and adds
+it to be preloaded into the wrapper script that executes the browser.
+
+Set the environment variable DLOPEN_WRAP_DEBUG=1 or DLOPEN_WRAP_DEBUG=2
+to get error/debug output from this library.

Added: trunk/Tools/Scripts/webkitpy/binary_bundling/dlopenwrap/dlopenwrap.c (0 => 292109)


--- trunk/Tools/Scripts/webkitpy/binary_bundling/dlopenwrap/dlopenwrap.c	                        (rev 0)
+++ trunk/Tools/Scripts/webkitpy/binary_bundling/dlopenwrap/dlopenwrap.c	2022-03-30 18:39:39 UTC (rev 292109)
@@ -0,0 +1,327 @@
+/*
+ * Copyright (C) 2022 Igalia S.L.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include <dirent.h>
+#include <dlfcn.h>
+#include <errno.h>
+#include <libgen.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#define dlopen_wrapper_print_error_msg(fmt, ...) \
+    do { \
+        if (dlopen_wrapper_debug_print >= 1) \
+            fprintf(stderr, "[pid=%d] ERROR at dlopenwrap.so: " fmt, getpid(), __VA_ARGS__); \
+    } while (0)
+
+#define dlopen_wrapper_print_debug_msg(fmt, ...) \
+    do { \
+        if (dlopen_wrapper_debug_print >= 2) \
+            fprintf(stderr, "[pid=%d] dlopenwrap.so: " fmt, getpid(), __VA_ARGS__); \
+    } while (0)
+
+static int dlopen_wrapper_debug_print = -1;
+static int dlopen_wrapper_call_real_dlerror = 1;
+static char* (*__real_dlerror)(void) = NULL;
+
+// Returns the string "dirname/filename" into the buffer path_joint_dest
+void dlopen_wrapper_path_join(const char* dirname, const char* filename, char* path_joint_dest)
+{
+    path_joint_dest = strncpy(path_joint_dest, dirname, PATH_MAX);
+    // add a slash if needed
+    if (*(path_joint_dest + strlen(dirname) - 1) != '/') {
+        *(path_joint_dest + strlen(dirname)) = '/';
+        *(path_joint_dest + strlen(dirname) + 1) = 0;
+    }
+    strncat(path_joint_dest, filename, PATH_MAX);
+}
+
+int is_dir(unsigned char d_type, const char* filepath)
+{
+    struct stat statbuf;
+    // we consider a symbolic link to a dir as a dir, also handle unknown.
+    if (d_type == DT_UNKNOWN || d_type == DT_LNK) {
+        if (stat(filepath, &statbuf))
+            dlopen_wrapper_print_error_msg("Calling stat on \"%s\": %s\n", filepath, strerror(errno));
+        return S_ISDIR(statbuf.st_mode);
+    }
+    return (d_type == DT_DIR);
+}
+
+// Recursive function to traverse a directory and obtain the path of the first file named "filename"
+// It writes that path to the buffer "candidate_path_dest" if the file is found (return == 1).
+// If the file is not found it returns 0 and the contents of "candidate_path_dest" are undefined.
+int dlopen_wrapper_recursive_find(const char* filename_to_find, const char* directory_to_search, char* candidate_path_dest)
+{
+
+    DIR *dp;
+    struct dirent* entry;
+
+    char subdirectory_to_search[PATH_MAX];
+    dp = opendir(directory_to_search);
+
+    if (!dp) {
+        dlopen_wrapper_print_error_msg("Opening directory \"%s\": %s\n", directory_to_search, strerror(errno));
+        return 0;
+    }
+
+    while (1) {
+        errno = 0;
+        entry = readdir(dp);
+        if (!entry) {
+            if (errno)
+                dlopen_wrapper_print_error_msg("Reading directory \"%s\": %s\n", directory_to_search, strerror(errno));
+            break;
+        }
+
+        if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
+            continue;
+
+        dlopen_wrapper_path_join(directory_to_search, entry->d_name, candidate_path_dest);
+
+        if (is_dir(entry->d_type, candidate_path_dest)) {
+            dlopen_wrapper_path_join(directory_to_search, entry->d_name, subdirectory_to_search);
+            if (dlopen_wrapper_recursive_find(filename_to_find, subdirectory_to_search, candidate_path_dest)) {
+                closedir(dp);
+                return 1;
+            }
+        } else {
+            if (!strcmp(filename_to_find, entry->d_name)) {
+                if (!access(candidate_path_dest, F_OK | R_OK)) {
+                    closedir(dp);
+                    return 1;
+                }
+                dlopen_wrapper_print_error_msg("Access denied to candidate library \"%s\"\n", candidate_path_dest);
+            }
+        }
+    }
+    closedir(dp);
+    return 0;
+}
+
+// Helper function that checks if filename_original_path is a path and is inside libdir.
+// If it can't find the file directly by the path, it calls dlopen_wrapper_recursive_find() to search it.
+// It writes the path to the buffer "path_found_dest" if the file is found (return == 1).
+// If the file is not found it returns 0 and the contents of "path_found_dest" are undefined.
+int dlopen_wrapper_get_path_for_file_under_dir(const char* filename_original_path, const char* libdir, char* path_found_dest)
+{
+
+    // basename() may modify the buffer passed on the first argument
+    char *original_path = strdup(filename_original_path);
+    char *base_file_to_dlopen_wrapper_find = basename(original_path);
+    int retcode = 1;
+    int filename_is_absolute = (*filename_original_path == '/');
+    int filename_is_relative = 0;
+    if (!filename_is_absolute) {
+        for (char* current_char = (char*)filename_original_path; *current_char; ++current_char) {
+            if (*current_char == '/') {
+                filename_is_relative = 1;
+                break;
+            }
+        }
+    }
+
+    if (filename_is_absolute) {
+        if (!strncmp(filename_original_path, libdir, strlen(libdir))) {
+            if (!access(filename_original_path, F_OK | R_OK)) {
+                dlopen_wrapper_print_debug_msg("Filename \"%s\" found under directory \"%s\" without any path rewriting\n", filename_original_path, libdir);
+                strncpy(path_found_dest, filename_original_path, PATH_MAX);
+                return 1;
+            }
+        }
+        dlopen_wrapper_print_debug_msg("Filename \"%s\" NOT found under directory \"%s\". Will try a search with basename\n", filename_original_path, libdir);
+    } else if (filename_is_relative) {
+        dlopen_wrapper_path_join(libdir, filename_original_path, path_found_dest);
+        if (!access(path_found_dest, F_OK | R_OK)) {
+            dlopen_wrapper_print_debug_msg("Filename \"%s\" converted to \"%s\" and found under directory \"%s\"\n", filename_original_path, path_found_dest, libdir);
+            return 1;
+        }
+        dlopen_wrapper_print_debug_msg("Filename \"%s\" NOT found under directory \"%s\"\n", filename_original_path, libdir);
+    }
+
+    dlopen_wrapper_print_debug_msg("Trying a search for basename \"%s\" under directory \"%s\"\n", base_file_to_dlopen_wrapper_find, libdir);
+
+    retcode = dlopen_wrapper_recursive_find(base_file_to_dlopen_wrapper_find, libdir, path_found_dest);
+    if (original_path)
+        free(original_path);
+    return retcode;
+}
+
+// Helper function to split the paths of ld_library_path and to search for "filename_original_path" inside those paths.
+// It will stop searching at the first match.
+// It writes the path to the buffer "path_found_dest" if the file is found (return == 1).
+// If the file is not found it returns 0 and the contents of "path_found_dest" are undefined.
+int dlopen_wrapper_find_library_on_libpath(const char* filename_original_path, const char* ld_library_path, char* path_found_dest)
+{
+
+    char *saveptr = NULL;
+    char *library_paths = strdup(ld_library_path);
+    int found = 0;
+
+    for (char *libdir = strtok_r(library_paths, ":", &saveptr); libdir; libdir = strtok_r(NULL, ":", &saveptr)) {
+        // make the path absolute
+        char *libdir_rp = realpath(libdir, NULL);
+        if (!libdir_rp) {
+            dlopen_wrapper_print_error_msg("Calling realpath() on \"%s\": %s\n", libdir, strerror(errno));
+            continue;
+        }
+        dlopen_wrapper_print_debug_msg("Trying search under directory %s\n", libdir);
+        if (dlopen_wrapper_get_path_for_file_under_dir(filename_original_path, libdir_rp, path_found_dest)) {
+            free(libdir_rp);
+            found = 1;
+            break;
+        }
+        free(libdir_rp);
+    }
+    free(library_paths);
+    return found;
+}
+
+void *dlopen(const char* filename, int flags)
+{
+    char new_file_path[PATH_MAX];
+    dlopen_wrapper_call_real_dlerror = 1;
+
+    if (dlopen_wrapper_debug_print == -1) {
+        char *dlopen_debug_value = getenv("DLOPEN_WRAP_DEBUG");
+        if (dlopen_debug_value)
+            dlopen_wrapper_debug_print = atoi(dlopen_debug_value);
+    }
+
+    static void* (*__real_dlopen)(const char* file, int mode) = NULL;
+    if (!__real_dlopen) {
+        __real_dlopen = dlsym(RTLD_NEXT, "dlopen");
+        if (!__real_dlopen) {
+            dlopen_wrapper_print_error_msg("Getting dlopen address: %s\n", dlerror());
+            dlopen_wrapper_call_real_dlerror = 0;
+            return NULL;
+        }
+    }
+    if (!__real_dlerror) {
+        __real_dlerror = dlsym(RTLD_NEXT, "dlerror");
+        if (!__real_dlerror) {
+            dlopen_wrapper_print_error_msg("Getting dlerror address: %s\n", dlerror());
+            return NULL;
+        }
+    }
+
+    // Don't do anything if filename is NULL or LD_LIBRARY_PATH not defined
+    if (!filename)
+        return __real_dlopen(filename, flags);
+
+    char *ld_library_path = getenv("LD_LIBRARY_PATH");
+    if (!ld_library_path)
+        return __real_dlopen(filename, flags);
+
+    if (!dlopen_wrapper_find_library_on_libpath(filename, ld_library_path, new_file_path)) {
+        dlopen_wrapper_print_error_msg("Could not find \"%s\" under the directori(es) of LD_LIBRARY_PATH. Refusing to dlopen it\n", filename);
+        dlopen_wrapper_call_real_dlerror = 0;
+        return NULL;
+    }
+
+    if (dlopen_wrapper_debug_print) {
+        if (strcmp(filename, new_file_path))
+            dlopen_wrapper_print_debug_msg("Original request to dlopen \"%s\" changed to load \"%s\"\n", filename, new_file_path);
+        else
+            dlopen_wrapper_print_debug_msg("Original request to dlopen \"%s\" allowed (unchanged) because is under the directori(es) of LD_LIBRARY_PATH\n", filename);
+    }
+
+    return __real_dlopen(new_file_path, flags);
+}
+
+void *dlmopen(Lmid_t lmid, const char* filename, int flags)
+{
+
+    char new_file_path[PATH_MAX];
+    dlopen_wrapper_call_real_dlerror = 1;
+
+    if (dlopen_wrapper_debug_print == -1) {
+        char *dlopen_debug_value = getenv("DLOPEN_WRAP_DEBUG");
+        if (dlopen_debug_value)
+            dlopen_wrapper_debug_print = atoi(dlopen_debug_value);
+    }
+
+    static void* (*__real_dlmopen)(Lmid_t lmidt, const char* file, int mode) = NULL;
+    if (!__real_dlmopen) {
+        __real_dlmopen = dlsym(RTLD_NEXT, "dlmopen");
+        if (!__real_dlmopen) {
+            dlopen_wrapper_print_error_msg("Getting dlmopen address: %s\n", dlerror());
+            dlopen_wrapper_call_real_dlerror = 0;
+            return NULL;
+        }
+    }
+    if (!__real_dlerror) {
+        __real_dlerror = dlsym(RTLD_NEXT, "dlerror");
+        if (!__real_dlerror) {
+            dlopen_wrapper_print_error_msg("Getting dlerror address: %s\n", dlerror());
+            return NULL;
+        }
+    }
+
+    // Don't do anything if filename is NULL or LD_LIBRARY_PATH not defined
+    if (!filename)
+        return __real_dlmopen(lmid, filename, flags);
+
+    char *ld_library_path = getenv("LD_LIBRARY_PATH");
+    if (!ld_library_path)
+        return __real_dlmopen(lmid, filename, flags);
+
+    if (!dlopen_wrapper_find_library_on_libpath(filename, ld_library_path, new_file_path)) {
+        dlopen_wrapper_print_error_msg("Could not find \"%s\" under the directori(es) of LD_LIBRARY_PATH. Refusing to dlmopen it\n", filename);
+        dlopen_wrapper_call_real_dlerror = 0;
+        return NULL;
+    }
+
+    if (dlopen_wrapper_debug_print) {
+        if (strcmp(filename, new_file_path))
+            dlopen_wrapper_print_debug_msg("Original request to dlmopen \"%s\" changed to load \"%s\"\n", filename, new_file_path);
+        else
+            dlopen_wrapper_print_debug_msg("Original request to dlmopen \"%s\" allowed (unchanged) because is under the directori(es) of LD_LIBRARY_PATH\n", filename);
+    }
+
+    return __real_dlmopen(lmid, new_file_path, flags);
+}
+
+
+char *dlerror(void)
+{
+    static char* wrapper_error_msg = "Call blocked by dlopenwrapper library.";
+
+    // __real_dlerror handle was already obtained before on the dlopen() or dlmopen() wrappers.
+    // Obtaining it here is not possible because calling dlsym() overwrites the dlerror buffer.
+    if (dlopen_wrapper_call_real_dlerror && __real_dlerror)
+        return __real_dlerror();
+
+    dlopen_wrapper_call_real_dlerror = 1;
+    return wrapper_error_msg;
+}

Modified: trunk/Tools/Scripts/webkitpy/style/checker.py (292108 => 292109)


--- trunk/Tools/Scripts/webkitpy/style/checker.py	2022-03-30 17:38:41 UTC (rev 292108)
+++ trunk/Tools/Scripts/webkitpy/style/checker.py	2022-03-30 18:39:39 UTC (rev 292109)
@@ -305,6 +305,11 @@
       os.path.join('Source', 'ThirdParty', 'libwebrtc', 'Source', 'webrtc'),
       os.path.join('Source', 'WebCore', 'PAL', 'pal', 'spi')],
      ["-readability/naming/underscores"]),
+
+    ([  # c code with underscores in variable names and tabs for the Makefile
+     os.path.join('Tools', 'Scripts', 'webkitpy', 'binary_bundling', 'dlopenwrap')],
+     ["-readability/naming/underscores",
+      "-whitespace/tab"]),
 ]
 
 
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to