520cc8
commit 841afa116e32b3c7195475769c26bf46fd870d32
520cc8
Author: Adhemerval Zanella <adhemerval.zanella@linaro.org>
520cc8
Date:   Wed Aug 10 16:24:06 2022 -0300
520cc8
520cc8
    glibcextract.py: Add compile_c_snippet
520cc8
    
520cc8
    It might be used on tests to check if a snippet build with the provided
520cc8
    compiler and flags.
520cc8
    
520cc8
    Reviewed-by: Florian Weimer <fweimer@redhat.com>
520cc8
520cc8
diff --git a/scripts/glibcextract.py b/scripts/glibcextract.py
520cc8
index 8f2246aae6a9dfb7..0fb50dc8f9c4f7f9 100644
520cc8
--- a/scripts/glibcextract.py
520cc8
+++ b/scripts/glibcextract.py
520cc8
@@ -17,6 +17,7 @@
520cc8
 # License along with the GNU C Library; if not, see
520cc8
 # <http://www.gnu.org/licenses/>.
520cc8
 
520cc8
+import collections
520cc8
 import os.path
520cc8
 import re
520cc8
 import subprocess
520cc8
@@ -173,3 +174,21 @@ def compare_macro_consts(source_1, source_2, cc, macro_re, exclude_re=None,
520cc8
             if not allow_extra_2:
520cc8
                 ret = 1
520cc8
     return ret
520cc8
+
520cc8
+CompileResult = collections.namedtuple("CompileResult", "returncode output")
520cc8
+
520cc8
+def compile_c_snippet(snippet, cc, extra_cc_args=''):
520cc8
+    """Compile and return whether the SNIPPET can be build with CC along
520cc8
+       EXTRA_CC_ARGS compiler flags.  Return a CompileResult with RETURNCODE
520cc8
+       being 0 for success, or the failure value and the compiler output.
520cc8
+    """
520cc8
+    with tempfile.TemporaryDirectory() as temp_dir:
520cc8
+        c_file_name = os.path.join(temp_dir, 'test.c')
520cc8
+        obj_file_name = os.path.join(temp_dir, 'test.o')
520cc8
+        with open(c_file_name, 'w') as c_file:
520cc8
+            c_file.write(snippet + '\n')
520cc8
+        cmd = cc.split() + extra_cc_args.split() + ['-c', '-o', obj_file_name,
520cc8
+                c_file_name]
520cc8
+        r = subprocess.run(cmd, check=False, stdout=subprocess.PIPE,
520cc8
+                stderr=subprocess.STDOUT)
520cc8
+        return CompileResult(r.returncode, r.stdout)