Clone of official tools

Revision:
43:2a7da56ebd24
Parent:
40:7d3fa6b99b2b
Child:
47:21ae3e5a7128
--- a/export/makefile/__init__.py	Mon Nov 06 13:17:14 2017 -0600
+++ b/export/makefile/__init__.py	Tue Sep 25 13:43:09 2018 -0500
@@ -14,6 +14,9 @@
 See the License for the specific language governing permissions and
 limitations under the License.
 """
+from __future__ import print_function, absolute_import
+from builtins import str
+
 from os.path import splitext, basename, relpath, join, abspath, dirname,\
     exists
 from os import remove
@@ -21,10 +24,20 @@
 from subprocess import check_output, CalledProcessError, Popen, PIPE
 import shutil
 from jinja2.exceptions import TemplateNotFound
+from tools.resources import FileType
 from tools.export.exporters import Exporter, apply_supported_whitelist
 from tools.utils import NotSupportedException
 from tools.targets import TARGET_MAP
 
+SHELL_ESCAPE_TABLE = {
+    "(": "\(",
+    ")": "\)",
+}
+
+
+def shell_escape(string):
+    return "".join(SHELL_ESCAPE_TABLE.get(char, char) for char in string)
+
 
 class Makefile(Exporter):
     """Generic Makefile template that mimics the behavior of the python build
@@ -66,7 +79,7 @@
                           self.resources.cpp_sources]
 
         libraries = [self.prepare_lib(basename(lib)) for lib
-                     in self.resources.libraries]
+                     in self.libraries]
         sys_libs = [self.prepare_sys_lib(lib) for lib
                     in self.toolchain.sys_libs]
 
@@ -84,28 +97,24 @@
                       if (basename(dirname(dirname(self.export_dir)))
                           == "projectfiles")
                       else [".."]),
-            'cc_cmd': " ".join(["\'" + part + "\'" for part
-                                in ([basename(self.toolchain.cc[0])] +
-                                    self.toolchain.cc[1:])]),
-            'cppc_cmd': " ".join(["\'" + part + "\'" for part
-                                  in ([basename(self.toolchain.cppc[0])] +
-                                      self.toolchain.cppc[1:])]),
-            'asm_cmd': " ".join(["\'" + part + "\'" for part
-                                in ([basename(self.toolchain.asm[0])] +
-                                    self.toolchain.asm[1:])]),
-            'ld_cmd': "\'" + basename(self.toolchain.ld[0]) + "\'",
-            'elf2bin_cmd': "\'" + basename(self.toolchain.elf2bin) + "\'",
+            'cc_cmd': basename(self.toolchain.cc[0]),
+            'cppc_cmd': basename(self.toolchain.cppc[0]),
+            'asm_cmd': basename(self.toolchain.asm[0]),
+            'ld_cmd': basename(self.toolchain.ld[0]),
+            'elf2bin_cmd': basename(self.toolchain.elf2bin),
             'link_script_ext': self.toolchain.LINKER_EXT,
             'link_script_option': self.LINK_SCRIPT_OPTION,
             'user_library_flag': self.USER_LIBRARY_FLAG,
             'needs_asm_preproc': self.PREPROCESS_ASM,
+            'shell_escape': shell_escape,
         }
 
         if hasattr(self.toolchain, "preproc"):
-            ctx['pp_cmd'] = " ".join(["\'" + part + "\'" for part
-                                      in ([basename(self.toolchain.preproc[0])] +
-                                          self.toolchain.preproc[1:] + 
-                                          self.toolchain.ld[1:])])
+            ctx['pp_cmd'] = " ".join(
+                [basename(self.toolchain.preproc[0])] +
+                self.toolchain.preproc[1:] +
+                self.toolchain.ld[1:]
+            )
         else:
             ctx['pp_cmd'] = None
 
@@ -121,6 +130,20 @@
                     'to_be_compiled']:
             ctx[key] = sorted(ctx[key])
         ctx.update(self.format_flags())
+        ctx['asm_flags'].extend(self.toolchain.asm[1:])
+        ctx['c_flags'].extend(self.toolchain.cc[1:])
+        ctx['cxx_flags'].extend(self.toolchain.cppc[1:])
+
+        # Add the virtual path the the include option in the ASM flags
+        new_asm_flags = []
+        for flag in ctx['asm_flags']:
+            if flag.startswith('-I'):
+                new_asm_flags.append("-I{}/{}".format(ctx['vpath'][0], flag[2:]))
+            elif flag.startswith('--preinclude='):
+                new_asm_flags.append("--preinclude={}/{}".format(ctx['vpath'][0], flag[13:]))
+            else:
+                new_asm_flags.append(flag)
+        ctx['asm_flags'] = new_asm_flags
 
         for templatefile in \
             ['makefile/%s_%s.tmpl' % (self.TEMPLATE,
@@ -140,8 +163,8 @@
     def format_flags(self):
         """Format toolchain flags for Makefile"""
         flags = {}
-        for k, v in self.flags.iteritems():
-            if k in ['asm_flags', 'c_flags', 'cxx_flags']:
+        for k, v in self.flags.items():
+            if k in ['c_flags', 'cxx_flags']:
                 flags[k] = map(lambda x: x.replace('"', '\\"'), v)
             else:
                 flags[k] = v
@@ -149,6 +172,15 @@
         return flags
 
     @staticmethod
+    def clean(_):
+        remove("Makefile")
+        # legacy .build directory cleaned if exists
+        if exists('.build'):
+            shutil.rmtree('.build')
+        if exists('BUILD'):
+            shutil.rmtree('BUILD')
+
+    @staticmethod
     def build(project_name, log_name="build_log.txt", cleanup=True):
         """ Build Make project """
         # > Make -j
@@ -169,7 +201,7 @@
         else:
             out_string += "FAILURE"
 
-        print out_string
+        print(out_string)
 
         if log_name:
             # Write the output to the log file
@@ -178,13 +210,8 @@
 
         # Cleanup the exported and built files
         if cleanup:
-            remove("Makefile")
             remove(log_name)
-            # legacy .build directory cleaned if exists
-            if exists('.build'):
-                shutil.rmtree('.build')
-            if exists('BUILD'):
-                shutil.rmtree('BUILD')
+            Makefile.clean(project_name)
 
         if ret_code != 0:
             # Seems like something went wrong.
@@ -228,10 +255,12 @@
 
     def generate(self):
         if self.resources.linker_script:
+            sct_file = self.resources.get_file_refs(FileType.LD_SCRIPT)[-1]
             new_script = self.toolchain.correct_scatter_shebang(
-                self.resources.linker_script)
-            if new_script is not self.resources.linker_script:
-                self.resources.linker_script = new_script
+                sct_file.path, join("..", dirname(sct_file.name)))
+            if new_script is not sct_file:
+                self.resources.add_files_to_type(
+                    FileType.LD_SCRIPT, [new_script])
                 self.generated_files.append(new_script)
         return super(Arm, self).generate()