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