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