taste-orchestrator.py 128 KB
Newer Older
1
2
3
4
5
#!/usr/bin/env python2
'''
This is the orchestrator that builds all TASTE systems - completely automating
the build process, invoking all necessary tools and code generators
'''
Maxime Perrotin's avatar
Maxime Perrotin committed
6
#
7
# Copyright (C) 2008-2015 Semantix Information Technologies, Neuropublic
Maxime Perrotin's avatar
Maxime Perrotin committed
8
# Copyright (C) 2008-2018 European Space Agency
9
# Copyright (c) 2014-2015 IB Krates <info@krates.ee>
Maxime Perrotin's avatar
Maxime Perrotin committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#
#
import sys
import os
import shutil
import getopt
import re
import hashlib
import traceback
import subprocess
import copy
import time
import glob
import logging
import multiprocessing
Thanassis Tsiodras's avatar
Thanassis Tsiodras committed
25
import xml.sax.saxutils
Maxime Perrotin's avatar
Maxime Perrotin committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

# File handle where build log (log.txt) is
g_log = None

# Flag to control whether we stop at each command or not (useful for debug)
g_bFast = False

# Flag controlling whether we abort on error, or wait for ENTER and retry
g_bRetry = True

# Flag controlling whether we use PO-HI-Ada or PO-HI-C
g_bPolyORB_HI_C = False

# Dictionary that contains the list of Functions per partition, e.g.
# { 'mypartition_obj142' : [ 'passive_function', 'cyclic_function' ] }
g_distributionNodes = {}

# Dictionary that contains elements for both partitions and functions,
# with the values being a pair of PLATFORM, GCC prefix, e.g.
#
# { 'mypartition_obj142' : ['PLATFORM_LEON_RTEMS', 'sparc-rtems4.8-'],
#   'passive_function' : ['PLATFORM_LEON_RTEMS', 'sparc-rtems4.8-'] }

g_distributionNodesPlatform = {}

# Dictionary that points to the containing partition of a function
# (the _objNNN suffix of TASTEIV is removed from the partition name)
#
# { 'passive_function' : 'mypartition' }
g_fromFunctionToPartition = {}

# Two dictionaries that are carrying lists of special flags
# (compilation/linking) per partition, e.g.
#
# { 'mypartition' : ['-I /path/to/include', '-D_DEBUG'] }
#
# The "--nodeOptions" command line arg modifies these (and we need
# human-readable strings, not _objNNN stuff - that's why the keys
# are the humanly-named targets, not the artificially suffixed ones)
g_customCFlagsPerNode = {}
g_customLDFlagsPerNode = {}

# Discussion in Mantis ticket 278: Julien suggests using the
# compilation flags detected via the RTEMS Makefile only for
# user code compilation - ocarina already has them and dies
# otherwise.
g_customCFlagsForUserCodeOnlyPerNode = {}

74
75
76
77
78
# Discussion in Mantis ticket 662: Adding env vars per deployment
# target and using them in the build - e.g.
#    RTEMS_MAKEFILE_PATH
g_envVarsPerNode = {}

Maxime Perrotin's avatar
Maxime Perrotin committed
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# Output folder we build in
g_absOutputDir = ""

# current build stage
g_currentStage = ""

# Python logging handler, to report build stages for Peter
g_stageLog = None


class ColorFormatter(logging.Formatter):
    # FORMAT = ("[%(levelname)-19s]  " "$BOLD%(filename)-20s$RESET" "%(message)s")
    # FORMAT    = ( "[%(levelname)-18s]  " "($BOLD%(filename)s$RESET:%(lineno)d)  " "%(message)s"  )
    FORMAT = ("[%(levelname)s]  " "$BOLD$RESET" "%(message)s")
    BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
    RESET_SEQ = "\x1b[0m"
    COLOR_SEQ = "\x1b[1;%dm"
    BOLD_SEQ = "\x1b[1m"
    COLORS = {
        'WARNING': YELLOW,
        'INFO': GREEN,
        'DEBUG': WHITE,
        'CRITICAL': RED,
        'ERROR': RED
    }

    def __init__(self, use_color):
        self.use_color = use_color
        msg = self.formatter_msg(self.FORMAT)
        logging.Formatter.__init__(self, msg)

110
111
112
113
114
    @staticmethod
    def bold_string(s):
        fore_color = 30 + ColorFormatter.COLORS['WARNING']
        return ColorFormatter.COLOR_SEQ % fore_color + s + ColorFormatter.RESET_SEQ

Maxime Perrotin's avatar
Maxime Perrotin committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    def formatter_msg(self, msg):
        if self.use_color:
            msg = msg.replace("$RESET", self.RESET_SEQ).replace("$BOLD", self.BOLD_SEQ)
        else:
            msg = msg.replace("$RESET", "").replace("$BOLD", "")
        return msg

    def format(self, record):
        levelname = record.levelname
        if self.use_color and levelname in self.COLORS:
            fore_color = 30 + self.COLORS[levelname]
            levelname_color = self.COLOR_SEQ % fore_color + levelname + self.RESET_SEQ
            record.levelname = levelname_color
        global g_currentStage
        g_currentStage = record.getMessage()
        return logging.Formatter.format(self, record)


def panic(x):
    '''Function called to abort with a message'''
    if not x.endswith("\n"):
        x += "\n"
    sys.stderr.write(x)
    g_stageLog.error(g_currentStage)
139
140
    if g_absOutputDir != "":
        os.system('env > "' + g_absOutputDir + os.sep + 'env.txt"')
Maxime Perrotin's avatar
Maxime Perrotin committed
141
142
143
144
145
146
147
148
149
150
151
152
153
154
    sys.exit(1)


def mysystem(x, outputDir=None):
    '''Spawns a cmd, logs it, and if it failed, will optionally retry it when ENTER is pressed'''
    global g_log
    if g_log is None:
        g_log = open(outputDir + os.sep + "log.txt", "w")
        return
    g_log.write("From: " + os.getcwd() + "\n")
    g_log.write(x + "\n")
    g_log.flush()
    while os.system(x) != 0:
        # Save the environment that was used for the failed command under OUTPUT_FOLDER/env.txt
155
156
        if g_absOutputDir != "":
            os.system('env > "' + g_absOutputDir + os.sep + 'env.txt"')
Maxime Perrotin's avatar
Maxime Perrotin committed
157
158
159
        if g_bRetry:
            if os.getenv('CLEANUP') is not None:
                print "Exception in user code:"
160
                print '-' * 60
Maxime Perrotin's avatar
Maxime Perrotin committed
161
                traceback.print_stack()
162
                print '-' * 60
Maxime Perrotin's avatar
Maxime Perrotin committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
            sys.stderr.write("Failed while executing:\n" + x + "\nFrom this directory:\n" + os.getcwd())
            sys.stdout.flush()
            sys.stderr.flush()
            if os.getenv('CLEANUP') is None:
                raw_input("\n\nPress ENTER to retry...")
            else:
                panic("\nFailed to compile...")
        else:
            panic("Failed while executing:\n" + x + "\nFrom this directory:\n" + os.getcwd())


def getSingleLineFromCmdOutput(cmd):
    try:
        f = os.popen(cmd)
        returnedLine = f.readlines()[0].strip()
178
        if f.close() is not None:
Maxime Perrotin's avatar
Maxime Perrotin committed
179
180
181
182
183
184
185
186
187
188
            print "Failed! Output was:\n", returnedLine
            raise Exception()
        return returnedLine
    except:
        panic("Failed to spawn '%s'" % cmd)


def banner(msg):
    '''Splashes message in big green letters'''
    if sys.stdout.isatty():
189
        print "\n" + chr(27) + "[32m" + msg + chr(27) + "[0m\n"
Maxime Perrotin's avatar
Maxime Perrotin committed
190
191
192
193
194
195
196
197
198
199
    else:
        print "\n" + msg + "\n"
    if not g_bFast:
        raw_input("Press ENTER to continue...")
    print "\n"
    sys.stdout.flush()


def usage():
    '''Shows all available cmd line arguments'''
200
    panic("TASTE/ASSERT orchestrator, revision: COMMITID\n"
Maxime Perrotin's avatar
Maxime Perrotin committed
201
202
203
204
205
206
207
208
209
210
211
          "Usage: " + os.path.basename(sys.argv[0]) + " <options>\nWhere <options> are:\n\n"
          "-f, --fast\n\tSkip waiting for ENTER between stages\n\n"
          "-g, --debug\n\tEnable debuging options\n\n"
          "-p, --with-polyorb-hi-c\n\tUse PolyORB-HI-C (instead of the default, PolyORB-HI-Ada)\n\n"
          "-r, --with-coverage\n\tUse GCC coverage options (gcov) for the generated applications\n\n"
          "-h, --gprof\n\tCreate binaries that can be profiled with gprof\n\n"
          "-o, --output outputDir\n\tDirectory with generated sources and code\n\n"
          "-i, --interfaceView i_view.aadl\n\tThe interface view in AADL\n\n"
          "-c, --deploymentView d_view.aadl\n\tThe deployment view in AADL\n\n"
          "-S, --subSCADE name:zipFile\n\ta zip file with the SCADE generated C code for a subsystem\n\twith the AADL name of the subsystem before the ':'\n\n"
          "-M, --subSIMULINK name:zipFile\n\ta zip file with the SIMULINK/ERT generated C code for a subsystem\n\twith the AADL name of the subsystem before the ':'\n\n"
212
          "-I, --subMicroPython name:zipFile\n\ta zip file with the MicroPython generated C code for a subsystem\n\twith the AADL name of the subsystem before the ':'\n\n"
Maxime Perrotin's avatar
Maxime Perrotin committed
213
214
215
216
217
218
219
220
221
222
          "-C, --subC name:zipFile\n\ta zip file with the C code for a subsystem\n\twith the AADL name of the subsystem before the ':'\n\n"
          "-B, --subCPP name:zipFile\n\ta zip file with the C++ code for a subsystem\n\twith the AADL name of the subsystem before the ':'\n\n"
          "-A, --subAda name:zipFile\n\ta zip file with the Ada code for a subsystem\n\twith the AADL name of the subsystem before the ':'\n\n"
          "-G, --subOG name:file1.pr<,file2.pr,...>\n\tObjectGeode PR files for a subsystem\n\twith the AADL name of the subsystem before the ':'\n\n"
          "-P, --subRTDS name:zipFile\n\ta zip file with the RTDS-generated code for a subsystem\n\twith the AADL name of the subsystem before the ':'\n\n"
          "-V, --subVHDL name\n\twith the AADL name of the VHDL subsystem\n\n"
          "-n, --nodeOptions name@debug=<on/off>@gcov=<on/off>@gprof=<on/off>@stackCheck=<on/off>\n\tcustom options per NODE (i.e. binary)\n\n"
          "-e, --with-extra-C-code deploymentPartition:directoryWithCfiles\n\tDirectory containing additional .c files to be compiled and linked in for deploymentPartition\n\n"
          "-d, --with-extra-Ada-code deploymentPartition:directoryWithADBfiles\n\tDirectory containing additional .adb files to be compiled and linked in for deploymentPartition\n\n"
          "-l, --with-extra-lib deploymentPartition:/path/to/libLibrary1.a<,/path/to/libLibrary2.a,...>\n\tAdditional libraries to be linked in for deploymentPartition\n\n"
223
224
          "-w, --with-cv-attributes properties_filename\n\tUpdate thread priorities, stack size and offset/phase during the build\n\n"
          "-x, --timer granularityInMilliseconds\n\tSet timer resolution (default: 100ms)")
Maxime Perrotin's avatar
Maxime Perrotin committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249


def md5hash(filename):
    '''Returns MD5 hash of input filename'''
    a = hashlib.md5()
    a.update(open(filename, 'r').read())
    return a.hexdigest()


def mkdirIfMissing(name):
    '''Creates a directory only if it is missing'''
    if not os.path.isdir(name):
        os.mkdir(name)


def mflags(node):
    '''Returns special link flags depending on the target platform of the desired target node'''
    if node not in g_distributionNodesPlatform:
        panic("%s did not exist in the 'nodes' file..." % node)
    kind, _ = g_distributionNodesPlatform[node]
    result = ""
    if kind.startswith("PLATFORM_LINUX32"):
        result += " -m32 "
    if kind == "PLATFORM_LINUX64":
        result += " -m64 "
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
    # As explained in the discussion in the RTEMS mailing list...
    #
    #     https://lists.rtems.org/pipermail/users/2016-February/029782.html
    #
    # ...there is no workaround: if you want to do SPARC FPU things (and we
    # almost universally do, in all missions now) you can't mix and match RTEMS
    # compiled with -msoft-float with code compiled without it. The latest
    # build (under /opt/rtems-4.12) packaged in the TASTE VM is from the
    # master branch of RTEMS4.12, with enabled SMP; and as recommended by
    # Embedded Brains in the above discussion, the leon2/leon3/ngmp.cfg config
    # files have been modified to compile for native FPU.
    #
    # if kind.startswith("PLATFORM_LEON_RTEMS"):
    #     result += " -msoft-float "
    #
265
    if kind.startswith("PLATFORM_GNAT_RUNTIME"):
266
        result += " -mfloat-abi=hard "
267
268
        # Cortex M4's FPU does not support double precision! if C code uses double,
        # it must be forced to use float instead:
269
270
        # Edit: this worked in gnat2016 but not in gnat2017
        # result += " -fshort-double "
Maxime Perrotin's avatar
Maxime Perrotin committed
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    return result


def handleXenomaiCommon(functionName, option):
    '''Returns special Xenomai compile/link flags if the input node is indeed a Xenomai one'''
    if functionName in g_distributionNodesPlatform:
        platform = g_distributionNodesPlatform[functionName][0]
        if platform.startswith("PLATFORM_LINUX32_XENOMAI"):
            skin = platform.split("_")[-1].lower()
            return " " + getSingleLineFromCmdOutput("xeno-config --skin=%s --%s" % (skin, option)) + " "
        else:
            return " "
    else:
        return " "


def handleXenomaiCflags(functionName):
    return handleXenomaiCommon(functionName, "cflags")


def handleXenomaiLDflags(functionName):
    return handleXenomaiCommon(functionName, "ldflags")


def handlePoHiC(functionName):
    '''Returns additional compilation flags for PO-HI-C builds'''
    if functionName not in g_distributionNodesPlatform:
        panic("%s did not exist in the 'nodes' file" % functionName)
    kind, _ = g_distributionNodesPlatform[functionName]

    extraCdirIncludes = ""
    polyorbActivityHpath = ""
    prefix = g_absOutputDir + "/GlueAndBuild/"
    for d in os.listdir(prefix):
        if os.path.isdir(prefix + d) and not d.startswith("glue"):
            polyorbActivityHpath = prefix + d
            break
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
    # In the past, we were looking for a folder under deploymentview_final
    # that started with the function name.
    #
    # This is not robust...

    # OBSOLETE
    # for d in os.listdir(polyorbActivityHpath):
    #     if os.path.isdir(polyorbActivityHpath + os.sep + d) and d.startswith(functionName):
    #         polyorbActivityHpath += os.sep + d
    #         break
    # else:

    # ...so we always check the 'nodes' info to see who is using this function.
    for partition in g_distributionNodes.keys():
        if functionName.lower() in [x.lower() for x in g_distributionNodes[partition]]:
            polyorbActivityHpath += os.sep + partition
Maxime Perrotin's avatar
Maxime Perrotin committed
324
325
            break
    else:
326
        polyorbActivityHpath = ""
Maxime Perrotin's avatar
Maxime Perrotin committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342

    if kind == "PLATFORM_X86_LINUXTASTE":
        extraCdirIncludes += " -I$LINUXTASTE_PATH/output//target/usr/local/include -DPOSIX"
    if g_bPolyORB_HI_C and polyorbActivityHpath != "":
        extraCdirIncludes += " -I " + polyorbActivityHpath
    if g_bPolyORB_HI_C:
        extraCdirIncludes += " -I " + getSingleLineFromCmdOutput("ocarina-config --prefix") + \
            "/include/ocarina/runtime/polyorb-hi-c/include/"
    return extraCdirIncludes


def CalculateCFLAGS(node, withPOHIC=True):
    '''Uses the previous functions to create the complete set of flags for a target node'''
    if node not in g_distributionNodesPlatform:
        panic("%s did not exist in the 'nodes' file" % node)
    kind, _ = g_distributionNodesPlatform[node]
343
    result = " -std=c99 " + mflags(node) + " "
Maxime Perrotin's avatar
Maxime Perrotin committed
344
345
346
    if g_bPolyORB_HI_C and withPOHIC:
        result += handlePoHiC(node) + " "
    result += handleXenomaiCflags(node)
347
348
    if "LINUX_DLL" in kind:
        result += "-fPIC"
Maxime Perrotin's avatar
Maxime Perrotin committed
349
350
351
352
353
354
    if "COMPCERT" in kind:
        result += "-DWORD_SIZE=4"
    if "NDS" in kind:
        result += " -mstructure-size-boundary=8 -mcpu=arm9tdmi -mfpu=vfp -mfloat-abi=soft -mthumb-interwork -g "
    if "GUMSTIX" in kind:
        result += " -mstructure-size-boundary=8 -mcpu=xscale -mfpu=vfp -mfloat-abi=soft -g "
355
    if "GNAT_RUNTIME" in kind:
356
        result += " -DNDEBUG "  # Not supported by AdaCore's CertyFlie...
357
358
        # STM32 CPUs do not not support double precision, make sure ASN1SCC uses floats
        result += " -DFP_WORD_SIZE=4 "
359
360
361
362
    else:
        # For heterogeneous systems (STM32+Native Linux) we must enforce size 8 on Native side
        # since the compiler is called once and it may have set --fp-word-size 4
        result += " -DFP_WORD_SIZE=8 "
363

Maxime Perrotin's avatar
Maxime Perrotin committed
364
365
366
367
368
369
370
371
    for binary, listOfFunctions in g_distributionNodes.items():
        key = re.sub(r'_obj\d+$', '', binary)
        if node == binary or node in listOfFunctions:
            # use custom options, if available
            if key in g_customCFlagsPerNode:
                result += ' '.join(g_customCFlagsPerNode[key])
                break
    # Let the user specify -fdata-sections -ffunction-sections if he wants.
372
373
    # if "-pg" not in result and not any(map(lambda x: x in kind, ["LEON", "COMPCERT"])):
    #    result += " -fdata-sections -ffunction-sections "
Maxime Perrotin's avatar
Maxime Perrotin committed
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
    return result


def CalculateUserCodeOnlyCFLAGS(node):
    '''Uses the previous functions to create the complete set of flags for a target node'''
    if node not in g_distributionNodesPlatform:
        panic("%s did not exist in the 'nodes' file" % node)
    result = " "
    for binary, listOfFunctions in g_distributionNodes.items():
        key = re.sub(r'_obj\d+$', '', binary)
        if node == binary or node in listOfFunctions:
            # use custom options, if available
            if key in g_customCFlagsForUserCodeOnlyPerNode:
                result += ' '.join(g_customCFlagsForUserCodeOnlyPerNode[key]) + ' '
                break
    return result


def SetEnvForRTEMS(platformType):
    try:
394
        src = None
Maxime Perrotin's avatar
Maxime Perrotin committed
395
396
397
398
399
400
401
402
403
404
405
406
        if platformType.startswith("PLATFORM_X86_RTEMS"):
            src = "RTEMS_MAKEFILE_PATH_X86"
            os.putenv("RTEMS_MAKEFILE_PATH", os.environ[src])
        elif platformType.startswith("PLATFORM_LEON_RTEMS"):
            src = "RTEMS_MAKEFILE_PATH_LEON"
            os.putenv("RTEMS_MAKEFILE_PATH", os.environ[src])
        elif platformType.startswith("PLATFORM_NDS_RTEMS"):
            src = "RTEMS_MAKEFILE_PATH_NDS"
            os.putenv("RTEMS_MAKEFILE_PATH", os.environ[src])
        elif platformType.startswith("PLATFORM_GUMSTIX_RTEMS"):
            src = "RTEMS_MAKEFILE_PATH_GUMSTIX"
            os.putenv("RTEMS_MAKEFILE_PATH", os.environ[src])
407
408
        if src is not None:
            RMP = os.environ[src]
409
410
411
            RCCPATH = os.sep.join(RMP.split(os.sep)[:-2] + ["bin"])
            if RCCPATH not in os.getenv("PATH"):
                os.putenv("PATH", RCCPATH + ":" + os.getenv("PATH"))
Maxime Perrotin's avatar
Maxime Perrotin committed
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
    except KeyError:
        panic("You must configure %s in your environment" % src)


def UpdateEnvForNode(node):
    '''Sets env vars GNAT{GCC,MAKE,BIND,LINK} and OBJCOPY, based on node's platform'''
    if node not in g_distributionNodesPlatform:
        panic("%s did not exist in the 'nodes' file" % node)
    kind, pref = g_distributionNodesPlatform[node]
    if kind == "PLATFORM_NATIVE_COMPCERT":
        os.putenv("GNATGCC", "ccomp")
    else:
        os.putenv("GNATGCC", pref + "gcc")
        os.putenv("GNATGXX", pref + "g++")
    os.putenv("GNATMAKE", pref + "gnatmake")
    os.putenv("GNATBIND", pref + "gnatbind")
    os.putenv("GNATLINK", pref + "gnatlink")
    os.putenv("OBJCOPY", pref + "objcopy")
    platformType = g_distributionNodesPlatform[node][0]
431
432
433
434
    if 'GNAT_RUNTIME' in platformType:
        os.putenv("ASN1SCC_FLAGS", " --fp-word-size 4 ")
    else:
        os.putenv("ASN1SCC_FLAGS", "")
Maxime Perrotin's avatar
Maxime Perrotin committed
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
    SetEnvForRTEMS(platformType)


def DetermineNumberOfCPUs():
    """ Number of virtual or physical CPUs on this system"""
    # Python 2.6+
    try:
        return multiprocessing.cpu_count()
    except (ImportError, NotImplementedError):
        pass

    # POSIX
    try:
        res = int(os.sysconf('SC_NPROCESSORS_ONLN'))
        if res > 0:
            return res
    except (AttributeError, ValueError):
        pass

    # Windows
    try:
        res = int(os.environ['NUMBER_OF_PROCESSORS'])
        if res > 0:
            return res
    except (KeyError, ValueError):
        pass

    # BSD
    try:
        sysctl = subprocess.Popen(['sysctl', '-n', 'hw.ncpu'], stdout=subprocess.PIPE)
        scStdout = sysctl.communicate()[0]
        res = int(scStdout)
        if res > 0:
            return res
    except (OSError, ValueError):
        pass

    # Linux
    try:
        res = open('/proc/cpuinfo').read().count('processor\t:')
        if res > 0:
            return res
    except IOError:
        pass

    # Solaris
    try:
        pseudoDevices = os.listdir('/devices/pseudo/')
        expr = re.compile('^cpuid@[0-9]+$')
        res = 0
        for pd in pseudoDevices:
            if expr.match(pd) is not None:
                res += 1
        if res > 0:
            return res
    except OSError:
        pass

    # Other UNIXes (heuristic)
    try:
        try:
            dmesg = open('/var/run/dmesg.boot').read()
        except IOError:
            dmesgProcess = subprocess.Popen(['dmesg'], stdout=subprocess.PIPE)
            dmesg = dmesgProcess.communicate()[0]
        res = 0
        while '\ncpu' + str(res) + ':' in dmesg:
            res += 1
        if res > 0:
            return res
    except OSError:
        pass

    raise Exception('Can not determine number of CPUs on this system')


patternCO = re.compile(r'^.*?<compiler-option>(.*?)</compiler-option>(.*)$')
patternLO = re.compile(r'^.*?<linker-option>(.*?)</linker-option>(.*)$')


def CheckDirectives(baseDir):
    '''Scans for and returns TASTE directives for additional compilation/linking flags'''
    if os.path.exists("../directives") and os.path.exists("../directives/directives.xml"):
        for line in open("../directives/directives.xml"):
            for pattern, target in [
                    (patternCO, g_customCFlagsPerNode),
                    (patternLO, g_customLDFlagsPerNode)]:
                data = line[:]
                while True:
                    findCO = re.match(pattern, data)
                    if findCO:
Thanassis Tsiodras's avatar
Thanassis Tsiodras committed
526
                        opt = xml.sax.saxutils.unescape(findCO.group(1))
Maxime Perrotin's avatar
Maxime Perrotin committed
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
                        data = findCO.group(2)
                        partition = g_fromFunctionToPartition[baseDir]
                        target.setdefault(partition, []).append(opt)
                    else:
                        break


def CommonBuildingPart(
    baseDir, toolDescription, CDirectories, cflagsSoFar,
    buildCmd=lambda baseDir, cf:
        mysystem("\"$GNATGCC\" -c %s -I ../../GlueAndBuild/glue%s/ -I ../../auto-src/ *.c" % (cf, baseDir))):

    '''The common build sequence for C, SCADE, Simulink'''

    if not os.path.isdir(baseDir):
        panic("No directory %s! (pwd=%s)" % (baseDir, os.getcwd()))
    if not os.path.isdir(baseDir + os.sep + baseDir):
        panic("%s zip file did not contain a %s dir..." % (toolDescription, baseDir))
    os.chdir(baseDir + os.sep + baseDir)
    CheckDirectives(baseDir)
    mysystem("for i in %s_vm_if.c %s_vm_if.h %s.h ; do if [ -f ../$i ] ; then cp ../$i . ; fi ; done" %
             (baseDir, baseDir, baseDir))
    mysystem("for i in hpredef.h invoke_ri.c ; do if [ -f ../$i ] ; then cp ../$i . ; fi ; done")
    mysystem("cp ../*polyorb_interface.? . 2>/dev/null || exit 0")
    mysystem("cp ../Context-*.? . 2>/dev/null || exit 0")
    mysystem("rm -f ../*-uniq.? *-uniq.? 2>/dev/null || exit 0")
    mysystem("rm -f ../dataview.[ch] dataview.* 2>/dev/null || exit 0")
    extraCdirIncludes = " "
    partitionName = g_fromFunctionToPartition[baseDir]
    if partitionName in CDirectories:
        for d in CDirectories[partitionName]:
558
            extraCdirIncludes += "-I \"" + d + "\" "
Maxime Perrotin's avatar
Maxime Perrotin committed
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
    if (baseDir in g_distributionNodesPlatform.keys()):
        UpdateEnvForNode(baseDir)
    cflags = cflagsSoFar + extraCdirIncludes + CalculateCFLAGS(baseDir) + CalculateUserCodeOnlyCFLAGS(baseDir)
    # Add include path to glue code
    cflags += " -I ../../GlueAndBuild/glue" + baseDir + "/ "
    buildCmd(baseDir, cflags)
    os.chdir("../..")


def BuildSCADEsystems(scadeSubsystems, CDirectories, cflagsSoFar):
    '''Compiles all user code for SCADE Functions'''
    if scadeSubsystems:
        g_stageLog.info("Building SCADE subSystems")
    for baseDir in scadeSubsystems.keys():
        CommonBuildingPart(baseDir, "SCADE", CDirectories, cflagsSoFar)


def BuildSimulinkSystems(simulinkSubsystems, CDirectories, cflagsSoFar, bUseSimulinkMakefiles):
    '''Compiles all user code for Simulink Functions'''
    if simulinkSubsystems:
        g_stageLog.info("Building Simulink subSystems")

    def buildCmdSimulink(baseDir, cf):
        if bUseSimulinkMakefiles[baseDir][0]:
            mysystem('make -f "' + bUseSimulinkMakefiles[baseDir][1] + '" assertBuild')
            if g_bPolyORB_HI_C:
                mysystem("\"$GNATGCC\" -c %s *polyorb_interface.c" % cf)
        else:
            mysystem("\"$GNATGCC\" -c %s *.c" % cf)
    for baseDir in simulinkSubsystems.keys():
        CommonBuildingPart(baseDir, "Simulink", CDirectories, cflagsSoFar, buildCmdSimulink)


592
593
594
595
596
597
def BuildMicroPythonSystems(micropythonSubsystems, CDirectories, cflagsSoFar):
    '''Compiles all user code for MicroPython Functions'''
    if micropythonSubsystems:
        g_stageLog.info("Building MicroPython subSystems")
    for baseDir in micropythonSubsystems.keys():

598
        mpySource = "$(taste-config --prefix)/../tool-src/upython-taste"
599
        mpyTemplDir = mpySource + "/ports/esa-taste"
600
601
602
603
604
605
606
607
608
609
610
        os.chdir(baseDir + os.sep + baseDir)

        if (baseDir in g_distributionNodesPlatform.keys()):
            UpdateEnvForNode(baseDir)

        # run mpy-cross to compile the MicroPython script, and then convert it C source
        mysystem("%s/mpy-cross/mpy-cross -v %s.py" % (mpySource, baseDir))
        with open("%s.mpy" % baseDir, "rb") as f:
            mpy_data = f.read()
        with open("%s.mpy.c" % baseDir, "wt") as f:
            f.write("const unsigned int mpy_script_len = %u;\n" % len(mpy_data))
Thanassis Tsiodras's avatar
Thanassis Tsiodras committed
611
            f.write("const unsigned char mpy_script_data[%u] = \"" % len(mpy_data))
612
613
614
615
            f.write("".join("\\x%02x" % ord(x) for x in mpy_data))
            f.write("\";\n")
        with open("%s.mpy.h" % baseDir, "wt") as f:
            f.write("extern const unsigned int mpy_script_len;\n")
Thanassis Tsiodras's avatar
Thanassis Tsiodras committed
616
            f.write("extern const unsigned char mpy_script_data[%u];\n" % len(mpy_data))
617
618
619

        # copy the MicroPython source
        mysystem("for file in %s/py/*.c; do cp $file ./py_$(basename $file); done" % (mpySource,))
Thanassis Tsiodras's avatar
Thanassis Tsiodras committed
620
        mkdirIfMissing("py")
621
622
623
624
625
626
        mysystem("for file in %s/py/*.h; do cp $file ./py/; done" % (mpySource,))

        # copy the bindings for this subsystem
        mysystem("for i in ../%s_mpy_bindings.[ch] ; do if [ -f $i ] ; then cp $i ./ ; fi ; done" % (baseDir,))

        # copy/generate mpconfigport.h, mphalport.h, and utility code
627
628
629
        mysystem("cp %s/mpconfigport_taste_x86.h ./mpconfigport.h" % (mpyTemplDir,))
        mysystem("cp %s/mphalport_taste_x86.h ./mphalport.h" % (mpyTemplDir,))
        mysystem("cp %s/mphalport_taste_x86.c ./mphalport.c" % (mpyTemplDir,))
630
631
632
633
634
635
636
637
638
639
640
641
642
643
        mysystem("cp %s/mputil.[ch] ./" % (mpyTemplDir,))

        # generate the interned qstrs
        mkdirIfMissing("genhdr")
        cflags = cflagsSoFar + " -I ../../GlueAndBuild/glue" + baseDir + "/ "
        mysystem("python %s/py/makeversionhdr.py ./genhdr/mpversion.h" % (mpySource,))
        mysystem("\"$GNATGCC\" -E -DNO_QSTR %s py_*.c %s_mpy_bindings.c > ./genhdr/qstr.i.last" % (cflags, baseDir))
        mysystem("python %s/py/makeqstrdefs.py split ./genhdr/qstr.i.last ./genhdr/qstr ./genhdr/qstrdefs.collected.h" % (mpySource,))
        mysystem("python %s/py/makeqstrdefs.py cat ./genhdr/qstr.i.last ./genhdr/qstr ./genhdr/qstrdefs.collected.h" % (mpySource,))
        mysystem("""cat ./py/qstrdefs.h ./genhdr/qstrdefs.collected.h | sed 's/^Q(.*)/"&"/' | "$GNATGCC" -E %s - | sed 's/^"\\(Q(.*)\\)"/\\1/' > ./genhdr/qstrdefs.preprocessed.h""" % (cflags,))
        mysystem("python %s/py/makeqstrdata.py ./genhdr/qstrdefs.preprocessed.h > ./genhdr/qstrdefs.generated.h" % (mpySource,))

        os.chdir("../..")

Thanassis Tsiodras's avatar
Thanassis Tsiodras committed
644
645
646
647
        CommonBuildingPart(baseDir, "MicroPython", CDirectories,
                           cflagsSoFar + " -std=c99 -Wno-switch -Wno-override-init -Wno-jump-misses-init",
                           buildCmd=lambda baseDir, cf:
                                    mysystem("\"$GNATGCC\" -c %s -Wno-switch-enum -I ../../GlueAndBuild/glue%s/ -I ../../auto-src/ *.c" % (cf, baseDir)))
648
649


Maxime Perrotin's avatar
Maxime Perrotin committed
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def BuildCsystems(cSubsystems, CDirectories, cflagsSoFar):
    '''Compiles all user code for C Functions'''
    if cSubsystems:
        g_stageLog.info("Building C subSystems")
    for baseDir in cSubsystems.keys():
        CommonBuildingPart(baseDir, "C", CDirectories, cflagsSoFar)


def BuildCPPsystems(cppSubsystems, CDirectories, cflagsSoFar):
    '''Compiles all user code for C++ Functions'''
    if cppSubsystems:
        g_stageLog.info("Building C++ subSystems")

    def buildCmdCPP(baseDir, cf):
        mysystem("\"$GNATGXX\" -c %s -I ../../GlueAndBuild/glue%s/ -I ../../auto-src/ *.cc" % (cf, baseDir))
        mysystem("\"$GNATGCC\" -c %s -I ../../GlueAndBuild/glue%s/ -I ../../auto-src/ *.c" % (cf, baseDir))
    for baseDir in cppSubsystems.keys():
        CommonBuildingPart(baseDir, "C++", CDirectories, cflagsSoFar, buildCmdCPP)


def BuildAdaSystems_C_code(adaSubsystems, unused_CDirectories, uniqueSetOfAdaPackages, cflagsSoFar):
    '''Compiles all C bridge code for Ada Functions (Ada user code compiled via Ocarina Makefiles)'''
    if adaSubsystems:
        g_stageLog.info("Building Ada subSystems")
    for baseDir in adaSubsystems.keys():
        if not os.path.isdir(baseDir):
            panic("No directory %s! (pwd=%s)" % (baseDir, os.getcwd()))
        if not os.path.isdir(baseDir + os.sep + baseDir):
            panic("Ada zip file did not contain a %s dir..." % (baseDir))
        os.chdir(baseDir + os.sep + baseDir)
        CheckDirectives(baseDir)
        mysystem("for i in `/bin/ls ../../GlueAndBuild/glue%s/*.ad? 2>/dev/null | grep -v '/asn1_'` ; do cp \"$i\"  . ; done" % baseDir)
682
        # mysystem("cp ../../GlueAndBuild/glue%s/asn1_types.ads ." % baseDir)
Maxime Perrotin's avatar
Maxime Perrotin committed
683
684
685
686
687
688
689
690
691
        mysystem("cp ../../GlueAndBuild/glue%s/adaasn1rtl.ad? . 2>/dev/null ; exit 0" % baseDir)
        for modulebase in uniqueSetOfAdaPackages.keys():
            mysystem("cp ../../GlueAndBuild/glue%s/%s.ad? . 2>/dev/null ; exit 0" % (baseDir, modulebase))
        mysystem("for i in %s_vm_if.c %s_vm_if.h vm_callback.c ; do if [ -f ../$i ] ; then cp ../$i . ; fi ; done" %
                 (baseDir, baseDir))
        mysystem("for i in hpredef.h invoke_ri.c vm_callback.h ; do if [ -f ../$i ] ; then cp ../$i . ; fi ; done")
        mysystem("cp ../*polyorb_interface.h . 2>/dev/null || exit 0")
        mysystem("rm -f ../dataview.ad[sb] 2>/dev/null || exit 0")
        # obsolete: compilation of Ada code is done via Ocarina's makefiles, not by the orchestrator
692
693
        # mysystem("\"$GNATGCC\" -g -c *.adb")
        # mysystem("for i in *.ads ; do [ ! -f ${i/.ads/.adb} ] && \"$GNATGCC\" -g -c *.ads || break ; done")
Maxime Perrotin's avatar
Maxime Perrotin committed
694
695
696
        if (baseDir in g_distributionNodesPlatform.keys()):
            UpdateEnvForNode(baseDir)
        mysystem("\"$GNATGCC\" -c %s -I ../../GlueAndBuild/glue%s/ -I ../../auto-src/ *.c" %
697
                 (cflagsSoFar + CalculateCFLAGS(baseDir) + CalculateUserCodeOnlyCFLAGS(baseDir), baseDir))
Maxime Perrotin's avatar
Maxime Perrotin committed
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
        os.chdir("..")
        cflags = cflagsSoFar + CalculateCFLAGS(baseDir) + CalculateUserCodeOnlyCFLAGS(baseDir)
        mysystem("\"$GNATGCC\" -c -I ../GlueAndBuild/glue%s/ -I ../auto-src/ %s *.c" % (baseDir, cflags))
        os.chdir("..")


def BuildObjectGeodeSystems(ogSubsystems, CDirectories, cflagsSoFar):
    '''Compiles all user code for ObjectGeode Functions'''
    if ogSubsystems:
        g_stageLog.info("Building ObjectGeode subSystems")
    for ss in ogSubsystems.keys():
        base = os.path.basename(ss)
        baseDir = os.path.splitext(base)[0]
        if not os.path.isdir(baseDir + os.sep + "ext"):
            panic("OG subsystems must contain an ext/ directory! (%s)" % str(ss))
        # This is for ObjectGeode code
        os.chdir(baseDir + os.sep + "ext")
        CheckDirectives(baseDir)
        mysystem("if [ ! -f \"$WORKDIR/GlueAndBuild/glue%s/OG_ASN1_Types.h\" ] ; then touch \"$WORKDIR/GlueAndBuild/glue%s/OG_ASN1_Types.h\" ; fi" % (ss, ss))
        mysystem("cp ../*polyorb_interface.? . 2>/dev/null || exit 0")
        mysystem("cp ../Context-*.? . 2>/dev/null || exit 0")
        mysystem("rm -f ../*-uniq.? *-uniq.? 2>/dev/null || exit 0")
        mysystem("rm -f ../dataview.[ch] 2>/dev/null || exit 0")
        extraCdirIncludes = " "
        partitionName = g_fromFunctionToPartition[baseDir]
        if partitionName in CDirectories:
            for d in CDirectories[partitionName]:
725
                extraCdirIncludes += "-I \"" + d + "\" "
Maxime Perrotin's avatar
Maxime Perrotin committed
726
727
728
        if (baseDir in g_distributionNodesPlatform.keys()):
            UpdateEnvForNode(baseDir)
        mysystem("for i in *.c ; do \"$GNATGCC\" -c %s -I \"$WORKDIR/auto-src/\"  -I \"$WORKDIR/GlueAndBuild/glue%s/\" \"$i\" || exit 1 ; done" %
729
                 (cflagsSoFar + extraCdirIncludes + CalculateCFLAGS(ss) + CalculateUserCodeOnlyCFLAGS(ss), ss))
Maxime Perrotin's avatar
Maxime Perrotin committed
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
        os.chdir("../..")


def BuildRTDSsystems(rtdsSubsystems, CDirectories, cflagsSoFar):
    '''Compiles all user code for PragmaDev Functions'''
    if rtdsSubsystems:
        g_stageLog.info("Building RTDS subSystems")
    for baseDir in rtdsSubsystems.keys():
        if not os.path.isdir(baseDir):
            panic("No directory %s! (pwd=%s)" % (baseDir, os.getcwd()))
        if not os.path.isdir(baseDir + os.sep + baseDir):
            panic("RTDS zip file did not contain a %s dir..." % (baseDir))
        os.chdir(baseDir + os.sep + baseDir)
        CheckDirectives(baseDir)
        mysystem("for i in common.h invoke_ri.c %s_vm_if.c %s_vm_if.h glue_%s.h glue_%s.c profile/RTDS_Proc.c ; do if [ -f ../$i ] ; then cp ../$i . ; fi ; done" %
                 (baseDir, baseDir, baseDir, baseDir))
        mysystem("cp ../*polyorb_interface.? . 2>/dev/null || exit 0")
        mysystem("cp ../Context-*.? . 2>/dev/null || exit 0")
        mysystem("rm -f ../*-uniq.? *-uniq.? 2>/dev/null || exit 0")
        mysystem("cp ../*syncRI.c . 2>/dev/null || exit 0")
        mysystem("rm -f ../dataview.[ch] 2>/dev/null || exit 0")
        extraCdirIncludes = " "
        partitionName = g_fromFunctionToPartition[baseDir]
        if partitionName in CDirectories:
            for d in CDirectories[partitionName]:
755
                extraCdirIncludes += "-I \"" + d + "\" "
Maxime Perrotin's avatar
Maxime Perrotin committed
756
757
758
        if (baseDir in g_distributionNodesPlatform.keys()):
            UpdateEnvForNode(baseDir)
        mysystem("\"$GNATGCC\" -c -DRTDS_NO_SCHEDULER %s %s -I ../../GlueAndBuild/glue%s/ -I ../../auto-src/ -I ../profile *.c" %
759
                 (cflagsSoFar + CalculateCFLAGS(baseDir) + CalculateUserCodeOnlyCFLAGS(baseDir), extraCdirIncludes, baseDir))
Maxime Perrotin's avatar
Maxime Perrotin committed
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
        os.chdir("../..")


def BuildVHDLsystems_C_code(vhdlSubsystems, CDirectories, cflagsSoFar):
    '''Compiles all C bridge code for VHDL Functions'''
    if vhdlSubsystems:
        g_stageLog.info("Building C code of VHDL subSystems")
    for baseDir in vhdlSubsystems.keys():
        if not os.path.isdir(baseDir):
            panic("No VHDL directory %s! (pwd=%s)" % (baseDir, os.getcwd()))
        os.chdir(baseDir)
        extraCdirIncludes = ""
        partitionName = g_fromFunctionToPartition[baseDir]
        if partitionName in CDirectories:
            for d in CDirectories[partitionName]:
775
                extraCdirIncludes += "-I \"" + d + "\" "
Maxime Perrotin's avatar
Maxime Perrotin committed
776
777
778
779
        if len([x for x in os.listdir(".") if x.endswith("polyorb_interface.c")])>0:
            if (baseDir in g_distributionNodesPlatform.keys()):
                UpdateEnvForNode(baseDir)
            mysystem("\"$GNATGCC\" -c %s %s -I ../GlueAndBuild/glue%s/ -I ../auto-src/ *.c" %
780
                     (cflagsSoFar + CalculateCFLAGS(baseDir) + CalculateUserCodeOnlyCFLAGS(baseDir), extraCdirIncludes, baseDir))
Maxime Perrotin's avatar
Maxime Perrotin committed
781
782
783
784
        os.chdir("..")


def BuildGUIs(guiSubsystems, cflagsSoFar, asn1Grammar):
785
    '''Builds automatically generated wxWdigets GUIs'''
Maxime Perrotin's avatar
Maxime Perrotin committed
786
787
788
789
790
791
    if guiSubsystems:
        g_stageLog.info("Building automatically created GUIs")
    for baseDir in guiSubsystems:
        if not os.path.isdir(baseDir):
            panic("No directory %s! (pwd=%s)" % (baseDir, os.getcwd()))
        # This is for GUI code
792
793
        if not os.path.exists(baseDir + os.sep + baseDir + "_gui_code.c"):
            panic("GUI generated code did not contain a %s ..." % (baseDir + os.sep + baseDir + "_gui_code.c"))
Maxime Perrotin's avatar
Maxime Perrotin committed
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
        os.chdir(baseDir)
        mkdirIfMissing("ext")
        mysystem('for i in * ; do if [ -f "$i" -a ! -e ext/"$i" ] ; then ln -s ../"$i" ext/ ; fi ; done')
        os.chdir("ext")
        partitionNameWithoutSuffix = g_fromFunctionToPartition.get(baseDir, None)
        if partitionNameWithoutSuffix:
            for k, v in g_distributionNodesPlatform.iteritems():
                if k.startswith(partitionNameWithoutSuffix):
                    platform = v[0]
                    break
            else:
                platform = None
            if platform == 'PLATFORM_WIN32':
                installPath = getSingleLineFromCmdOutput("taste-config --prefix")
                mysystem("%s/share/gui-udp/build_gui_glue.py %s" % (installPath, baseDir))
                mysystem('cp "%s"/share/gui-udp/udpcontroller.? .' % installPath)
            else:
                mysystem("cp \"$DMT\"/AutoGUI/queue_manager.? .")
        mysystem("cp ../*polyorb_interface.? . 2>/dev/null || exit 0")
        mysystem("cp ../Context-*.? . 2>/dev/null || exit 0")
        mysystem("rm -f ../*-uniq.? *-uniq.? 2>/dev/null || exit 0")
        if (baseDir in g_distributionNodesPlatform.keys()):
            UpdateEnvForNode(baseDir)
        mysystem("\"$GNATGCC\" -c %s -I ../../GlueAndBuild/glue%s/ -I ../../auto-src/ *.c" %
                 (cflagsSoFar + CalculateCFLAGS(baseDir) + CalculateUserCodeOnlyCFLAGS(baseDir), baseDir))
        os.chdir("..")
        # Now create the controlling GUI application
        mkdirIfMissing("GUI")
        mysystem('for i in * ; do if [ -f "$i" -a ! -e GUI/"$i" ] ; then ln -s ../"$i" GUI/ ; fi ; done')
        os.chdir("GUI")
        mysystem("cp \"$DMT\"/AutoGUI/* .")
        mysystem("cat Makefile | sed 's,DataView,%s,g' > a_temp_name && mv a_temp_name Makefile" % os.path.splitext(os.path.basename(asn1Grammar))[0])
826
        mysystem("cat Makefile | sed 's,applicationName,%s,g' > a_temp_name && mv a_temp_name Makefile" % (baseDir + "_GUI"))
Maxime Perrotin's avatar
Maxime Perrotin committed
827
        mysystem("cp -u ../../GlueAndBuild/glue" + baseDir + "/C_*.[ch] .")
828
        # mysystem("cp ../auto-src/* .")
Maxime Perrotin's avatar
Maxime Perrotin committed
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
        if baseDir.endswith('probe_console'):
            os.chdir("../..")
            continue
        os.chdir("../..")


def BuildPythonStubs(pythonSubsystems, asn1Grammar, acnFile):
    '''Builds automatically generated Python stubs'''
    if pythonSubsystems:
        g_stageLog.info("Building automatically created Python stubs")
    for baseDir in pythonSubsystems:
        if not os.path.isdir(baseDir):
            panic("No directory %s! (pwd=%s)" % (baseDir, os.getcwd()))
        olddir = os.getcwd()
        pattern = re.compile(r'.*?glue([^/]*)')
        findFV = re.match(pattern, baseDir)
        if findFV:
            FVname = findFV.group(1)
        else:
            panic("Could not detect FVname out of '%s'" % baseDir)
        os.chdir(baseDir)
        mysystem("cp \"$DMT\"/AutoGUI/queue_manager.? .")
        mysystem("cp \"$DMT\"/AutoGUI/timeInMS.? .")
        mysystem("cp \"$DMT\"/AutoGUI/debug_messages.? .")
        mysystem("cp \"%s\"/%s/%s_enums_def.h ." % (g_absOutputDir, FVname, FVname))
        mysystem("cp \"%s\" ." % asn1Grammar)
        mysystem("cp \"%s\" ." % acnFile)
        mkdirIfMissing("asn2dataModel")
857
        mysystem("asn2dataModel -o asn2dataModel -toPython " + os.path.basename(asn1Grammar))
Maxime Perrotin's avatar
Maxime Perrotin committed
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
        os.chdir("asn2dataModel")
        mysystem("cp \"%s\" ." % acnFile)

        guiName = re.sub(r'^.*/glue(.*)/.*$', '\\1', baseDir)
        partitionNameWithoutSuffix = g_fromFunctionToPartition.get(guiName, None)
        if partitionNameWithoutSuffix:
            for k, v in g_distributionNodesPlatform.iteritems():
                if k.startswith(partitionNameWithoutSuffix):
                    platform = v[0]
                    break
            else:
                platform = None
            if platform == 'PLATFORM_WIN32':
                installPath = getSingleLineFromCmdOutput("taste-config --prefix")
                mysystem('cp "%s"/share/gui-udp/Makefile.python .' % installPath)
        mysystem("cp \"%s\"/%s/interface_enum.h ." % (g_absOutputDir, FVname))
874
        mysystem("make -f Makefile.python")
Maxime Perrotin's avatar
Maxime Perrotin committed
875
        os.chdir("..")
876
        mysystem("cp asn2dataModel/asn1crt.h asn2dataModel/Stubs.py asn2dataModel/DV* asn2dataModel/*.so .")
Maxime Perrotin's avatar
Maxime Perrotin committed
877
878
        mysystem("cp asn2dataModel/%s.h ." % os.path.splitext(os.path.basename(asn1Grammar))[0])
        mysystem("cp asn2dataModel/%s_asn.py ." % os.path.splitext(os.path.basename(asn1Grammar))[0].replace("-", "_"))
879
880
881
882
883
        # mysystem("swig  -Wall -includeall -outdir . -python ./PythonAccess.i")
        # mysystem("gcc -g -fPIC -c `python-config --cflags` gui_api.c queue_manager.c timeInMS.c debug_messages.c PythonAccess_wrap.c")
        mysystem("gcc -g -fPIC -c `python-config --cflags` gui_api.c queue_manager.c timeInMS.c debug_messages.c")
        # mysystem("gcc -g -shared -o _PythonAccess.so PythonAccess_wrap.o gui_swig.o queue_manager.o timeInMS.o debug_messages.o `python-config --ldflags` -lrt")
        mysystem("gcc -g -shared -o PythonAccess.so gui_api.o queue_manager.o timeInMS.o debug_messages.o `python-config --ldflags` -lrt")
Maxime Perrotin's avatar
Maxime Perrotin committed
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
        os.chdir(olddir)


def BuildCyclicSubsystems(cyclicSubsystems, cflagsSoFar):
    '''Compiles code of Cyclic Functions'''
    if cyclicSubsystems:
        g_stageLog.info("Building cyclic subSystems")
    for baseDir in cyclicSubsystems:
        if not os.path.isdir(baseDir):
            panic("No directory %s! (pwd=%s)" % (baseDir, os.getcwd()))
        # This is for automatically generated Cyclic code
        os.chdir(baseDir + os.sep)
        if (baseDir in g_distributionNodesPlatform.keys()):
            UpdateEnvForNode(baseDir)
        if 0 != len([x for x in os.listdir(".") if x.endswith(".c")]):
            mysystem("\"$GNATGCC\" -c %s -I ../GlueAndBuild/glue%s/ -I ../auto-src/ *.c" %
                     (cflagsSoFar + CalculateCFLAGS(baseDir) + CalculateUserCodeOnlyCFLAGS(baseDir), baseDir))
        os.chdir("..")


904
def RenameCommonlyNamedSymbols(scadeSubsystems, simulinkSubsystems, micropythonSubsystems, cSubsystems, cppSubsystems, adaSubsystems, rtdsSubsystems, ogSubsystems, guiSubsystems, cyclicSubsystems, vhdlSubsystems):
Maxime Perrotin's avatar
Maxime Perrotin committed
905
906
907
908
909
910
911
912
913
914
915
916
    '''Identifies and renames identical symbols in separate subsystems'''
    g_stageLog.info("Renaming commonly named symbols")

    def getTarget(baseDir):
        if baseDir in ogSubsystems or baseDir in guiSubsystems:
            return "/ext/"
        elif baseDir in cyclicSubsystems or baseDir in vhdlSubsystems:
            return os.sep
        else:
            return os.sep + baseDir + os.sep

    prefixes = {}
917
    for baseDir in scadeSubsystems.keys() + simulinkSubsystems.keys() + micropythonSubsystems.keys() + cSubsystems.keys() + cppSubsystems.keys() + \
Maxime Perrotin's avatar
Maxime Perrotin committed
918
919
920
921
922
923
924
            adaSubsystems.keys() + rtdsSubsystems.keys() + ogSubsystems.keys() + \
            guiSubsystems + cyclicSubsystems + vhdlSubsystems.keys():
        if baseDir not in g_distributionNodesPlatform:
            panic("%s did not exist in the 'nodes' file" % baseDir)
        systemPlatform, pref = g_distributionNodesPlatform[baseDir]
        prefixes[pref] = systemPlatform
        appendTarget = getTarget(baseDir)
925
926
        if 0 != len([x for x in os.listdir("GlueAndBuild/glue" + baseDir) if x.endswith(".o")]):
            mysystem("mv GlueAndBuild/glue" + baseDir + "/*.o " + baseDir + appendTarget)
Maxime Perrotin's avatar
Maxime Perrotin committed
927
928
929

    for prefix, systemPlatform in prefixes.items():
        renamingDirs = 0
930
        cmd = "patchAPLCs.py "
931
        for baseDir in scadeSubsystems.keys() + simulinkSubsystems.keys() + micropythonSubsystems.keys() + cSubsystems.keys() + cppSubsystems.keys() + \
Maxime Perrotin's avatar
Maxime Perrotin committed
932
933
934
935
936
937
938
939
940
941
942
943
944
945
                adaSubsystems.keys() + rtdsSubsystems.keys() + ogSubsystems.keys() + \
                guiSubsystems + cyclicSubsystems + vhdlSubsystems.keys():
            _, pref = g_distributionNodesPlatform[baseDir]
            if pref != prefix:
                continue
            appendTarget = getTarget(baseDir)
            cmd += ' "' + baseDir + appendTarget + '"'
            cmd += ' "' + baseDir.replace(' ', '_') + '_renamed"'
            renamingDirs += 1
            if baseDir not in adaSubsystems:
                cmd += ' "' + baseDir + appendTarget + '"'
                cmd += ' "' + baseDir.replace(' ', '_') + '"'
                renamingDirs += 1
        if renamingDirs > 1:
946
            os.putenv("OBJCOPY", prefix + "objcopy")
Maxime Perrotin's avatar
Maxime Perrotin committed
947
948
949
950
951
952
953
954
            asn1SccFolder = "auto-src_" + systemPlatform
            if os.path.isdir(asn1SccFolder):
                cmd += ' ' + asn1SccFolder + "/"
                cmd += ' ' + asn1SccFolder
            mysystem(cmd)


def InvokeOcarinaMakefiles(
955
    scadeSubsystems, simulinkSubsystems, micropythonSubsystems, cSubsystems, cppSubsystems, adaSubsystems, rtdsSubsystems, ogSubsystems, guiSubsystems, cyclicSubsystems, vhdlSubsystems,
Maxime Perrotin's avatar
Maxime Perrotin committed
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
        cflagsSoFar, CDirectories, AdaDirectories, AdaIncludePath, ExtraLibraries,
        bDebug, bUseEmptyInitializers, bCoverage, bProfiling):

    '''Invokes Makefiles generated by Ocarina - generates final executable code'''
    g_stageLog.info("Invoking Ocarina generated Makefiles")
    os.chdir(g_absOutputDir)
    os.chdir("GlueAndBuild")
    for root, _, files in os.walk("."):
        for _ in [x for x in files if x.lower() == "makefile"]:
            # Learn the name of the AADL system
            node = ""
            for line in open(root + os.sep + "Makefile").readlines():
                line = line.strip()
                if line.startswith("#  Node name"):
                    node = line[34:]
971
972
973
            if node == "":
                # Handle LaTEX-doxygen related Makefiles (closes: #488)
                continue
Maxime Perrotin's avatar
Maxime Perrotin committed
974
975
976
977
978
979
980
981
982
983
            if node not in g_distributionNodes:
                panic("There is no '%s' node in the distribution nodes generated by buildsupport." % node)

            partitionNameWithoutSuffix = re.sub(r'_obj\d+$', '', node)

            # Create the EXTERNAL_OBJECTS line
            externals = ""
            userCFlags = "-g " if bDebug else ""
            userLDFlags = "-g " if bDebug else ""

984
985
986
987
            # VCD support
            if bDebug and g_bPolyORB_HI_C:
                userCFlags += "-D__PO_HI_USE_VCD=1 "

Maxime Perrotin's avatar
Maxime Perrotin committed
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
            # Profiling: Either the global "--gprof" has been used,
            # or the node-specific "-n nodeName@gprof=on" has been used.
            # or no profiling is needed.

            # Has the user asked for this specific node to be profiled?
            nodeIsGPROFed = partitionNameWithoutSuffix in g_customCFlagsPerNode and \
                "-pg" in g_customCFlagsPerNode[partitionNameWithoutSuffix]
            # Or maybe the user passed "--gprof" ?
            nodeIsGPROFed = nodeIsGPROFed or bProfiling
            # In either case, setup profiling:
            if nodeIsGPROFed:
                userCFlags += " -D__PO_HI_USE_GPROF "
                os.putenv("USE_GPROF", "1")
                if g_distributionNodesPlatform[node][0].startswith("PLATFORM_LEON_RTEMS"):
                    userCFlags += " -I " + os.getenv("RTEMS_MAKEFILE_PATH_LEON") + "/lib/include/ "
            else:
                # Otherwise disable it
                os.unsetenv("USE_GPROF")
            # If global ("--gprof") profiling is set, add "-pg" to CFLAGS and LDFLAGS
            if bProfiling:
                userCFlags += " -pg "
                userLDFlags += " -pg "

            # With AADLv2, we support multi-platform builds, so we must compile the code with the appropriate compiler
            UpdateEnvForNode(node)
            olddir = os.getcwd()

            # Check to see if we are using pohic and building a system with Ada parts.
            bNeedAdaBuildWorkaround = False
            for aplc in g_distributionNodes[node]:
                if aplc in adaSubsystems.keys():
                    if g_bPolyORB_HI_C:
                        bNeedAdaBuildWorkaround = True
                        break

            os.chdir("..")
            asn1target = "auto-src_" + g_distributionNodesPlatform[node][0]
            asn1target = os.path.abspath(asn1target)
            poHiAdaLinkCmd = ""
1027
            poHiAdaLinkLibs = ""
Maxime Perrotin's avatar
Maxime Perrotin committed
1028
1029
1030
1031
1032
1033
            # in case of rebuilds
            mysystem("rm -rf \"%s\" 2>/dev/null ; exit 0" % asn1target)
            if not os.path.exists(asn1target):
                os.mkdir(asn1target)
                os.chdir(asn1target)
                mysystem("cp ../auto-src/*.[ch] .")
1034
                mysystem("\"$GNATGCC\" -c %s *.c" % (cflagsSoFar + CalculateCFLAGS(node) + CalculateUserCodeOnlyCFLAGS(node)))
Maxime Perrotin's avatar
Maxime Perrotin committed
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
                os.chdir("..")

            if bNeedAdaBuildWorkaround:
                os.chdir(asn1target)
                for baseDir, ss in adaSubsystems.items():
                    if baseDir not in g_distributionNodes[node]:
                        continue
                    mysystem("cp ../GlueAndBuild/glue" + baseDir + "/*.adb . 2>/dev/null || exit 0")
                    mysystem("cp ../GlueAndBuild/glue" + baseDir + "/*.ads . 2>/dev/null || exit 0")
                TasteAda = open('tasteada.ads', 'w')
                for baseDir, ss in adaSubsystems.items():
                    if baseDir not in g_distributionNodes[node]:
                        continue
                    TasteAda.write('with %s;\n' % baseDir)
                TasteAda.write('package TasteAda is\n')
                TasteAda.write('end TasteAda;\n')
                TasteAda.close()
1052
1053
                # open("conf.ec",'w').write("pragma No_Run_Time;\n")
                # mysystem("gnatmake -c -I../../auto-src " + baseDir + " " + x + " -gnatec=conf.ec")
1054
                mysystem("\"$GNATMAKE\" -c %s -I.  -gnat2012 tasteada.ads" % mflags(node))
Maxime Perrotin's avatar
Maxime Perrotin committed
1055
1056
1057
1058
                if not os.path.exists("tasteada.ali"):
                    panic("WARNING: No tasteada.ali file was generated")
                mysystem("\"$GNATBIND\" -t -n tasteada.ali -o ada-start.adb")
                dbg = "-g" if bDebug else ""
1059
                mysystem("\"$GNATMAKE\" -c %s %s -gnat2012 ada-start.adb" % (dbg, mflags(node)))
Maxime Perrotin's avatar
Maxime Perrotin committed
1060
1061
                for line in open("ada-start.adb").readlines():
                    if -1 != line.find("adalib"):
1062
                        poHiAdaLinkCmd = line.strip().replace("--", "")
Maxime Perrotin's avatar
Maxime Perrotin committed
1063
                        runtimePath = " " + line.strip().replace("-L", "-Wl,-R") + " "
1064
                        poHiAdaLinkCmd += runtimePath.replace("--", "")
Maxime Perrotin's avatar
Maxime Perrotin committed
1065
1066
1067
                if poHiAdaLinkCmd == "":
                    panic("There was no line containing 'adalib' inside 'ada-start.adb'")
                poHiAdaLinkCmd += " -lgnat -lgnarl"
1068
1069
1070
1071
1072
1073

                # Patch from Jerome, after latest updates in POHI:
                # RTEMS builds expect user-provided libraries to be provided through the LD_LIBS macro,
                # other PolyORB-HI/C can use directly USER_LDFLAGS
                poHiAdaLinkLibs += " LD_LIBS=\"-lgnat -lgnarl\" "

Maxime Perrotin's avatar
Maxime Perrotin committed
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
                os.chdir("..")

            externals += asn1target + '/*.o '
            if g_distributionNodesPlatform[node][0] in ("PLATFORM_LINUX32",):  # and platform.architecture()[0] == '64bit':
                userCFlags += ' -m32 '
                userLDFlags += ' -m32 '
            userLDFlags += handleXenomaiLDflags(node)
            os.chdir(olddir)

            for aplc in g_distributionNodes[node]:
1084
                for baseDir in scadeSubsystems.keys() + simulinkSubsystems.keys() + micropythonSubsystems.keys() + cSubsystems.keys() + cppSubsystems.keys() + adaSubsystems.keys() + rtdsSubsystems.keys():
Maxime Perrotin's avatar
Maxime Perrotin committed
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
                    if baseDir == aplc:
                        if g_bPolyORB_HI_C and baseDir in adaSubsystems:
                            if 0 != len([x for x in os.listdir(g_absOutputDir + os.sep + baseDir + os.sep + baseDir + os.sep) if x.endswith('.o')]):
                                externals += g_absOutputDir + os.sep + baseDir + os.sep + baseDir + os.sep + '*.o '
                            if 0 != len([x for x in os.listdir(g_absOutputDir + os.sep + baseDir + os.sep) if x.endswith('.o')]):
                                for u in ("%s_vm_if.o" % baseDir, "invoke_ri.o"):
                                    mysystem("rm -f %s/%s" % (g_absOutputDir + os.sep + baseDir + os.sep, u))
                                externals += g_absOutputDir + os.sep + baseDir + os.sep + '*.o '
                        else:
                            externals += g_absOutputDir + os.sep + baseDir + os.sep + baseDir + os.sep + '*.o '
                for ss in ogSubsystems.keys():
                    if ss == aplc:
                        base = os.path.basename(ss)
                        baseDir = os.path.splitext(base)[0]
                        externals += g_absOutputDir + os.sep + baseDir + os.sep + "ext" + os.sep + '*.o '
                for ss in guiSubsystems:
                    if ss == aplc:
                        base = os.path.basename(ss)
                        baseDir = os.path.splitext(base)[0]
                        externals += g_absOutputDir + os.sep + baseDir + os.sep + "ext" + os.sep + '*.o '
                for ss in cyclicSubsystems:
                    if ss == aplc:
                        base = os.path.basename(ss)
                        baseDir = os.path.splitext(base)[0]
                        if 0 != len([x for x in os.listdir(g_absOutputDir + os.sep + baseDir + os.sep) if x.endswith('.c')]):
                            externals += g_absOutputDir + os.sep + baseDir + os.sep + '*.o '
                for vhdlSubsystem in vhdlSubsystems.keys():
                    if vhdlSubsystem == aplc:
                        base = os.path.basename(vhdlSubsystem)
                        baseDir = os.path.splitext(base)[0]
                        externals += g_absOutputDir + os.sep + baseDir + os.sep + '*.o '

            # Extra C code
            if partitionNameWithoutSuffix in CDirectories:
                for extraCdir in CDirectories[partitionNameWithoutSuffix]:
                    g_stageLog.info("Compiling additional C code in '%s'..." % extraCdir)
                    if len([x for x in os.listdir(extraCdir) if x.endswith(".c")])!=0:
                        pwd = os.getcwd()
                        os.chdir(extraCdir)
                        # banner("You use AADLv2 and external code, I don't know what flags to compile it with!!!")
                        if bUseEmptyInitializers:
1126
                            mysystem("\"$GNATGCC\" %s -c -DEMPTY_LOCAL_INIT *.c" % (CalculateCFLAGS(node) + CalculateUserCodeOnlyCFLAGS(node)))
Maxime Perrotin's avatar
Maxime Perrotin committed
1127
                        else:
1128
                            mysystem("\"$GNATGCC\" %s -c *.c" % (CalculateCFLAGS(node) + CalculateUserCodeOnlyCFLAGS(node)))
Maxime Perrotin's avatar
Maxime Perrotin committed
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
                        os.chdir(pwd)

            if partitionNameWithoutSuffix in CDirectories:
                for extraCdir in CDirectories[partitionNameWithoutSuffix]:
                    if len([x for x in os.listdir(extraCdir) if x.endswith(".o")])!=0:
                        externals += extraCdir + '/*.o '

            if partitionNameWithoutSuffix in AdaDirectories:
                for extraADAdir in AdaDirectories[partitionNameWithoutSuffix]:
                    if len([x for x in os.listdir(extraADAdir) if x.endswith(".o")])!=0:
                        externals += extraADAdir + '/*.o '

            if partitionNameWithoutSuffix in ExtraLibraries:
                extraLibs = ExtraLibraries[partitionNameWithoutSuffix]
                if extraLibs != []:
                    externals += ' '.join(extraLibs) + ' '

            for aplc in g_distributionNodes[node]:
                if aplc in vhdlSubsystems.keys():
                    if g_bPolyORB_HI_C:
1149
1150
                        # externals += ' "' + getSingleLineFromCmdOutput("echo $DMT").strip() + '/OG/libESAFPGAforC.a" '
                        externals += ' "' + getSingleLineFromCmdOutput("echo $DMT").strip() + '/ZestSC1/libZestSC1.a" /lib/i386-linux-gnu/libusb-0.1.so.4 '
Maxime Perrotin's avatar
Maxime Perrotin committed
1151
                    else:
1152
1153
                        # externals += ' "' + getSingleLineFromCmdOutput("echo $DMT").strip() + '/OG/libESAFPGA.a" '
                        externals += ' "' + getSingleLineFromCmdOutput("echo $DMT").strip() + '/ZestSC1/libZestSC1.a" /lib/i386-linux-gnu/libusb-0.1.so.4'
Maxime Perrotin's avatar
Maxime Perrotin committed
1154
1155
1156
1157
1158
1159
1160
1161
                    break  # If you meet even one VHDL component for this node, the library was added to externals, no need to check further

            userCFlags += mflags(node)
            userLDFlags += mflags(node)

            if g_bPolyORB_HI_C and len(adaSubsystems) != 0:
                userLDFlags += poHiAdaLinkCmd

1162
            # mysystem("cd '"+root+"' && cp ../../../*/*_sync.ads .")
Maxime Perrotin's avatar
Maxime Perrotin committed
1163
1164
1165
1166
1167
1168
1169
            driversConfigPath = os.path.abspath("../DriversConfig/")
            if os.path.exists(driversConfigPath):
                driversConfigs = os.listdir(driversConfigPath)
                for dC in driversConfigs:
                    if AdaIncludePath is None:
                        AdaIncludePath = driversConfigPath + "/" + dC
                    else:
1170
                        AdaIncludePath += ":" + driversConfigPath + "/" + dC
Maxime Perrotin's avatar
Maxime Perrotin committed
1171

1172
1173
1174
1175
            if AdaIncludePath is None:
                cmd = "cd '" + root + "' && %s EXTERNAL_OBJECTS=\""
            else:
                cmd = "cd '" + root + "' && ADA_INCLUDE_PATH=\"" + AdaIncludePath + "\" %s EXTERNAL_OBJECTS=\""
Maxime Perrotin's avatar
Maxime Perrotin committed
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
            # Just before invoking ocarina-generated Makefiles, make sure that only one C_ASN1_Types.o is used:
            externalFiles = ' '.join(x for x in externals.split(' ') if not x.startswith("-"))
            os.system("rm -f `/bin/ls %s | grep C_ASN1_Types.o | sed 1d` ; exit 0" % externalFiles)

            extra = ""

            platformType = g_distributionNodesPlatform[node][0]
            if platformType.startswith("PLATFORM_X86_RTEMS"):
                os.putenv("RTEMS_MAKEFILE_PATH", os.environ["RTEMS_MAKEFILE_PATH_X86"])
            elif platformType.startswith("PLATFORM_LEON_RTEMS"):
                os.putenv("RTEMS_MAKEFILE_PATH", os.environ["RTEMS_MAKEFILE_PATH_LEON"])
            elif platformType.startswith("PLATFORM_NDS_RTEMS"):
                os.putenv("RTEMS_MAKEFILE_PATH", os.environ["RTEMS_MAKEFILE_PATH_NDS"])
            elif platformType.startswith("PLATFORM_GUMSTIX_RTEMS"):
                os.putenv("RTEMS_MAKEFILE_PATH", os.environ["RTEMS_MAKEFILE_PATH_GUMSTIX"])
1191
            if all(x not in platformType for x in ["LEON", "RTEMS", "WIN32", "GNAT_RUNTIME"]):
Maxime Perrotin's avatar
Maxime Perrotin committed
1192
                extra += "-lrt "
Delia Cellarier's avatar
Delia Cellarier committed
1193
            if "GNAT_RUNTIME" not in platformType:
Delia Cellarier's avatar
Delia Cellarier committed
1194
1195
                # some symbols from libgnat seem to conflict with libm
                userLDFlags += " -lm "
Maxime Perrotin's avatar
Maxime Perrotin committed
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
            if bCoverage:
                extra += " -lgcov "
            if platformType in ("PLATFORM_LINUX32",):  # and platform.architecture()[0] == '64bit':
                userCFlags += " -m32 "
                userLDFlags += " -m32 "
            if g_bPolyORB_HI_C and platformType in \
                    ("PLATFORM_LINUX32", "PLATFORM_LINUX64", "PLATFORM_X86_RTEMS", "PLATFORM_X86_LINUXTASTE", "PLATFORM_NATIVE"):
                if not bDebug:
                    userLDFlags += " -Wl,-gc-sections "
                else:
                    userCFlags += " -g "
                    userLDFlags += " -g "
            if partitionNameWithoutSuffix in g_customLDFlagsPerNode:
                userLDFlags += " " + " ".join(g_customLDFlagsPerNode[partitionNameWithoutSuffix]) + " "
            if partitionNameWithoutSuffix in g_customCFlagsPerNode:
                userCFlags += " " + " ".join(g_customCFlagsPerNode[partitionNameWithoutSuffix]) + " "
            if g_bPolyORB_HI_C and cflagsSoFar != "":
                userCFlags += " " + cflagsSoFar.replace('"', '\\"') + " "
            userCFlags = userCFlags.strip()
            if userCFlags != "":
1216
                userCFlags = ' ' + userCFlags
Maxime Perrotin's avatar
Maxime Perrotin committed
1217
1218
            userLDFlags = userLDFlags.strip()
            if userLDFlags != "":
1219
                userLDFlags = ' ' + userLDFlags
Maxime Perrotin's avatar
Maxime Perrotin committed
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237

            if len(cppSubsystems)>0:
                userLDFlags += " -lstdc++ "

            # Workaround for bug in the new GNAT - crashes if it sees multiple -m32
            def keepOnlyFirstCompilationOption(flags):
                cmd = ""
                tokensUnique = {}
                for token in flags.split():
                    if token.startswith("-") and not token.startswith("-I"):
                        if token not in tokensUnique:
                            tokensUnique[token] = 1
                            cmd += " " + token
                    else:
                        cmd += " " + token
                return cmd + " "
            userCFlags = keepOnlyFirstCompilationOption(userCFlags)
            userLDFlags = keepOnlyFirstCompilationOption(userLDFlags)
1238
            if "GNAT_RUNTIME" in platformType:
1239
1240
1241
1242
1243
                userCFlags = userCFlags.replace(" -mfloat-abi=hard ", " ")  # Not supported when compiling Ada
                userLDFlags = userLDFlags.replace(" -mfloat-abi=hard ", " ")  # Not supported when compiling Ada
                userCFlags = userCFlags.replace("-fshort-double", " ")  # Not supported when compiling Ada
                userLDFlags = userLDFlags.replace("-fshort-double", " ")  # Not supported when compiling Ada
                userLDFlags = userLDFlags.replace("-lstdc++", " ")  # Not supported when compiling Ada
Maxime Perrotin's avatar
Maxime Perrotin committed
1244
            customFlags = (' USER_CFLAGS="${USER_CFLAGS}%s" USER_LDFLAGS="${USER_LDFLAGS}%s"' % (userCFlags, userLDFlags))
1245
            mysystem((cmd % customFlags) + extra + externals + "\"" + poHiAdaLinkLibs + " make")
Maxime Perrotin's avatar
Maxime Perrotin committed
1246
1247
1248
    return AdaIncludePath


Thanassis Tsiodras's avatar
Thanassis Tsiodras committed
1249
def GatherAllExecutableOutput(unused_outputDir, pythonSubsystems, vhdlSubsystems, tmpDirName, bDebug, i_aadlFile):
Maxime Perrotin's avatar
Maxime Perrotin committed
1250
1251
1252
1253
1254
    '''Gathers all binaries generated (Ocarina,GUIs,Python,PeekPoke,etc) and moves them under .../binaries'''
    g_stageLog.info("Gathering all executable output")
    outputDir = g_absOutputDir
    os.chdir(outputDir)
    mkdirIfMissing(outputDir + os.sep + "/binaries")
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
    os.chdir("..")
    if len(vhdlSubsystems)>0:
        msg = "VHDL bit files built:"
        g_stageLog.info('-' * len(msg))
        g_stageLog.info(msg)
        cmd = "find '%s' -type f -iname '*bit'" % " ".join(vhdlSubsystems.keys())
        for line in os.popen(cmd).readlines():
            line = line.strip()
            targetFolder = outputDir + os.sep + "binaries" + os.sep
            mysystem('cp "' + line + '" "' + targetFolder + '"')
            print "        " + ColorFormatter.bold_string(targetFolder + os.path.basename(line))
    os.chdir(outputDir)
1267
    mysystem("find '%s'/GlueAndBuild -type f -perm /111 ! -iname '*.so' -a ! -iname '*.pyd' | while read ANS ; do file \"$ANS\" | egrep 'ELF|PE32' >/dev/null 2>/dev/null && mv \"$ANS\" \"%s/binaries/\" ; done ; exit 0" % (g_absOutputDir, g_absOutputDir))
TASTE User's avatar
TASTE User committed
1268
    mysystem("find '%s'/ -name binaries -prune -o -type f -perm /111 -iname '*_GUI' -exec bash -c 'F=\"{}\"; D=$(dirname \"$F\"); B=$(basename \"$F\") ; B=\"${B/_GUI/}\"; mv \"$F\" \"%s/binaries/\" ; mv \"$D\"/../../../${B}.pl \"%s/binaries/\" ; mv \"$D\"/../../../${B}_RunAndPlot.sh \"%s/binaries/\" ; ' ';' 2>/dev/null" % (g_absOutputDir, g_absOutputDir, g_absOutputDir, g_absOutputDir))
1269
1270
1271
1272
1273
1274
1275
1276
1277
    # if len(pythonSubsystems)>0:
    #     msg = "Python bridges built under %s:" % outputDir
    #     g_stageLog.info('-' * len(msg))
    #     g_stageLog.info(msg)
    #     g_stageLog.info("Python bridges built under %s:" % outputDir)
    #     for line in os.popen("find '%s' -type f -iname PythonAccess.so -perm /111" % (g_absOutputDir)).readlines():
    #         g_stageLog.info("        Shared library: " + line.strip())

    # g_stageLog.info('-' * 70)
Maxime Perrotin's avatar
Maxime Perrotin committed
1278
1279
1280
1281
1282
1283
1284
1285
    # Strip binaries:
    if not bDebug:
        for n in g_distributionNodesPlatform.keys():
            if os.path.exists(outputDir + os.sep + "/binaries" + os.sep + n):
                pref = g_distributionNodesPlatform[n][1]
                mysystem("%sstrip %s" % (pref, outputDir + os.sep + "/binaries" + os.sep + n))
    if bDebug:
        g_stageLog.info("Built with debug info: you can check the stack usage of the binaries")
1286
        g_stageLog.info("with 'checkStackUsage.py', to make sure you are within limits.")
Maxime Perrotin's avatar
Maxime Perrotin committed
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
    # ticket 224: Keep gnuplot stuff separate
    olddir = os.getcwd()
    os.chdir(outputDir + os.sep + "/binaries/")
    for i in os.listdir("."):
        if i.endswith("_GUI"):
            base = i.replace("_GUI", "")
            mysystem('mkdir -p "GnuPlot_%s"' % base)
            # These two moves may fail if the only TM/TCs carry ENUMERATED - how to plot one?!?
            mysystem('mv "%s_RunAndPlot.sh" "GnuPlot_%s"/ >/dev/null 2>&1 ; exit 0' % (base, base))
            mysystem('mv "%s.pl" "GnuPlot_%s"/  >/dev/null 2>&1 ; exit 0' % (base, base))
    os.chdir(olddir)

1299
1300
1301
    # Jerome's "DLL" section
    mysystem("find '%s'/GlueAndBuild/deployment* -type f -perm /111 -iname '*.so' | while read ANS ; do file \"$ANS\" | egrep 'ELF|PE32' >/dev/null 2>/dev/null && mv \"$ANS\" \"%s/binaries/\" ; done ; exit 0" % (g_absOutputDir, g_absOutputDir))

Maxime Perrotin's avatar
Maxime Perrotin committed
1302
1303
1304
1305
1306
1307
1308
1309
1310
    # Peek and Poke section preparation
    mkdirIfMissing(outputDir + os.sep + "/binaries/PeekPoke")
    os.chdir(outputDir + os.sep + "/binaries/PeekPoke")
    for line in os.popen("find ../.. -type d -name gluetaste_probe_console").readlines():
        line = line.strip()
        mysystem('cp "%s"/python/*.py "%s"/python/*.so .' % (line, line))
        installPath = getSingleLineFromCmdOutput("taste-config --prefix")
        mysystem('cp "%s"/bin/taste-gnuplot-streams ./driveGnuPlotsStreams.pl' % installPath)
        mysystem('for i in peekpoke.py PeekPoke.glade ; do cp "%s"/share/peekpoke/$i . ; done' % installPath)
1311
        # mysystem('echo Untaring pyinstaller.speedometer.tar.bz2... ; tar jxf "%s"/share/speedometer/pyinstaller.speedometer.tar.bz2' % installPath)
Maxime Perrotin's avatar
Maxime Perrotin committed
1312
1313
1314
1315
1316
1317
1318
1319
1320
        g_stageLog.info("A PeekPoke subfolder was also created under binaries")
        g_stageLog.info("for easy run-time monitoring and control of inner variables.")
        break
    os.chdir("..")
    if [] == os.listdir("PeekPoke"):
        os.rmdir("PeekPoke")

    g_stageLog.info("Executables built under %s/binaries:" % outputDir)
    for line in os.popen(
1321
            "find '%s'/binaries -type f -perm /111 | grep -v /PeekPoke/ ; exit 0" % (g_absOutputDir)).readlines():
Maxime Perrotin's avatar
Maxime Perrotin committed
1322
        line = line.strip()
1323
1324
        if any(x in line
               for x in ['/GUI-', 'PythonAccess.so', 'dataview-uniq_getset.so']):
Maxime Perrotin's avatar
Maxime Perrotin committed
1325
            continue
1326
        print "        " + ColorFormatter.bold_string(line.strip())
Maxime Perrotin's avatar
Maxime Perrotin committed
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337

    mysystem("rm -rf \"%s\"" % tmpDirName)
    if len(os.popen("find '%s/GlueAndBuild/' -type f -name guilayout.ui" % outputDir).readlines()):
        g_stageLog.info("Gathering new Python-based GUIs")

        for guiFName in os.popen("find '%s/GlueAndBuild/' -type f -name 'guilayout.ui' | sed 's,/guilayout.ui,,;s,^.*/glue,,'" % outputDir).readlines():
            if guiFName.strip().endswith('probe_console'):
                continue
            guiFName = guiFName.strip()
            stubs = {
                'gui': guiFName,
1338
1339
1340
                'glue': outputDir + '/GlueAndBuild/glue' + guiFName + '/',
                'target': outputDir + "/binaries/" + guiFName + "-GUI",
                'GUItarget': outputDir + "/binaries/GUI-" + guiFName,
Maxime Perrotin's avatar
Maxime Perrotin committed
1341
                'IFview': i_aadlFile,
1342
                'DView': outputDir + "/dataview-uniq.asn"
Maxime Perrotin's avatar
Maxime Perrotin committed
1343
1344
1345
1346
1347
            }
            mysystem('mkdir -p "%(target)s"' % stubs)
            mysystem('cp "%(glue)s/"*.py "%(target)s"' % stubs)
            mysystem('cp "%(glue)s/guilayout.ui" "%(target)s"' % stubs)
            mysystem('cp "%(glue)s/python/"*.py "%(target)s"' % stubs)
1348
            mysystem('echo "errCodes = $(taste-asn1-errCodes %(glue)s/python/dataview-uniq.h)" >> "%(target)s/datamodel.py"' % stubs)
Maxime Perrotin's avatar
Maxime Perrotin committed
1349
1350
1351
            mysystem('cp "%(glue)s/python/"*.so "%(target)s"' % stubs)
            mysystem('cp "%(glue)s/python/asn2dataModel/"*.pyd "%(target)s" 2>/dev/null || exit 0' % stubs)
            mysystem('cp "%(glue)s/python/asn2dataModel/"*.so "%(target)s" 2>/dev/null || exit 0' % stubs)
1352
1353
1354
1355
1356
            mysystem('cp "%(glue)s/python/asn2dataModel/"DV_Types.py "%(target)s" 2>/dev/null || exit 0' % stubs)
#            mysystem('cp -r "$(taste-config --prefix)/share/speedometer/content" "%(target)s"' % stubs)
#            mysystem('cp -r "$(taste-config --prefix)/share/speedometer/dialcontrol.qml" "%(target)s"' % stubs)
            mysystem('echo \'A=$(dirname "$0") ; cd "$A/%(gui)s-GUI" && PYTHONPATH=$(taste-config --prefix)/share:$PYTHONPATH taste-gui "$@"\' > "%(GUItarget)s" && chmod +x "%(GUItarget)s"' % stubs)
#            mysystem('cp "$(taste-config --prefix)/share/asn1-editor/tasteLogo_white.png" "%(target)s"' % stubs)
Maxime Perrotin's avatar
Maxime Perrotin committed
1357
1358
1359
1360
            mysystem('cp "%(IFview)s" "%(target)s"/InterfaceView.aadl' % stubs)
            mysystem('cp "%(IFview)s" "%(target)s"/InterfaceView.aadl' % stubs)
            mysystem('cp "%(DView)s" "%(target)s"/' % stubs)

1361
        for line in os.popen("find '%s'/binaries/ -maxdepth 1 -type f -perm /111 -name 'GUI*' ; exit 0" % (g_absOutputDir)):
1362
            print "        " + ColorFormatter.bold_string(line.strip())
Maxime Perrotin's avatar
Maxime Perrotin committed
1363
1364


1365
1366
1367
1368
1369
1370
def CopyDatabaseFolderIfExisting():
    if os.path.isdir(g_absOutputDir + "/../sql_db"):
        for line in os.popen("find '%s'/binaries/ -maxdepth 1 -type d -iname '*GUI' ; exit 0" % (g_absOutputDir)):
            mysystem("cp -al \"%s\" \"%s\"" % (g_absOutputDir + "/../sql_db/", line.strip()))


Maxime Perrotin's avatar
Maxime Perrotin committed
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
def FixEnvVars():
    '''Updates required environment variables'''
    # DMT tarball is now obsolete - we will use the repos-provided
    # versions of the DMT tools
    DMTpath = getSingleLineFromCmdOutput("taste-config --prefix") + os.sep + "share"
    os.putenv("DMT", DMTpath)

    # ObjectGeode variables
    os.putenv("GEODE_MAPPING", "TP")
    os.putenv("GEODE_MULTI_BIN", "0")
    os.putenv("GEODE_REMOTE_CREATE", "0")
    os.putenv("GEODE_NAME_LIMIT", "30")
    os.putenv("GEODE_LINE_SIZE", "80")
    os.putenv("GEODE_STR_SIZE", "40")
    os.putenv("GEODE_ANSI_FUNCTION", "1")
    os.putenv("GEODE_PRS_HOOK", "0")
    os.putenv("GEODE_FILE_SIGNAL", "0")
    os.putenv("GEODE_FILE_PROCED", "0")
    os.putenv("GEODE_DEC_ONLINE", "0")
    os.putenv("GEODE_CVISS", "0")
    os.putenv("GEODE_FIELD_PREFIX", "fd_")
    os.putenv("GEODE_OUTPUT_FUNCTION", "0")
    os.putenv("GEODE_OUTPUT_TASK", "0")
    os.putenv("GEODE_SCHED_MODE", "0")
    os.putenv("GEODE_C_CHARSTRING", "0")
    os.putenv("GEODE_NBPAR_NODE", "0")
    os.putenv("GEODE_NBPAR_GROUP", "0")
    os.putenv("GEODE_NBPAR_TASK", "0")
    os.putenv("GEODE_NBPAR_EXTERN", "0")
    os.putenv("GEODE_NBPAR_PROC", "0")


1403
1404
def ParseCommandLineArgs():
    '''Parses options passed in the command line'''
Maxime Perrotin's avatar
Maxime Perrotin committed
1405
1406
1407
    disableColor = "--nocolor" in sys.argv
    if disableColor:
        sys.argv.remove("--nocolor")
1408
    global g_stageLog
Maxime Perrotin's avatar
Maxime Perrotin committed
1409
1410
1411
1412
1413
1414
1415
1416
1417
    g_stageLog = logging.getLogger("tasteBuilder")
    console = logging.StreamHandler(sys.__stdout__)
    console.setFormatter(ColorFormatter(sys.stdin.isatty() and not disableColor))
    g_stageLog.setLevel(logging.INFO)
    g_stageLog.addHandler(console)

    g_stageLog.info("Parsing Command Line Args")
    try:
        args = sys.argv[1:]
1418
        optlist, args = getopt.gnu_getopt(args, "fgpbrvhjn:o:c:i:S:M:I:C:B:A:G:P:V:QC:QA:e:d:l:w:x:", ['fast', 'debug', 'no-retry', 'with-polyorb-hi-c', 'with-empty-init', 'with-coverage', 'aadlv2', 'gprof', 'keep-case', 'nodeOptions=', 'output=', 'deploymentView=', 'interfaceView=', 'subSCADE=', 'subSIMULINK=', 'subMicroPython=', 'subC=', 'subCPP=', 'subAda=', 'subOG=', 'subRTDS=', 'subVHDL=', 'subQGenC=', 'subQGenAda=', 'with-extra-C-code=', 'with-extra-Ada-code=', 'with-extra-lib=', 'with-cv-attributes', '--timer='])
Maxime Perrotin's avatar
Maxime Perrotin committed
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
    except:
        usage()
    if args != []:
        usage()  # some args were not understood

    global g_bFast, g_bPolyORB_HI_C
    g_bFast = g_bPolyORB_HI_C = False
    global g_bRetry
    g_bRetry = True  # set by default
    bUseEmptyInitializers = bCoverage = bProfiling = bDebug = bKeepCase = False
1429
1430
1431
1432
1433

    # Maxime request: never check for multicores anymore, POHI updates fixed the issues.
    enableMultiCoreCheck = False
    # if os.getenv("DISABLE_MULTICORE_CHECK") is not None:
    #     enableMultiCoreCheck = False
Maxime Perrotin's avatar
Maxime Perrotin committed
1434
1435
1436
1437
1438

    outputDir = ""
    depl_aadlFile = ""
    i_aadlFile = ""
    cvAttributesFile = ""
1439
    timerResolution = "100"
Maxime Perrotin's avatar
Maxime Perrotin committed
1440
1441
    scadeSubsystems = {}
    simulinkSubsystems = {}
1442
    micropythonSubsystems = {}
Maxime Perrotin's avatar
Maxime Perrotin committed
1443
    cSubsystems = {}
1444
1445
    qgencSubsystems = {}
    qgenadaSubsystems = {}
Maxime Perrotin's avatar
Maxime Perrotin committed
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
    cppSubsystems = {}
    adaSubsystems = {}
    ogSubsystems = {}
    rtdsSubsystems = {}
    vhdlSubsystems = {}
    AdaIncludePath = os.getenv("ADA_INCLUDE_PATH")
    CDirectories = {}
    AdaDirectories = {}
    ExtraLibraries = {}

    for opt, arg in optlist:
        if opt in ("-f", "--fast"):
            g_bFast = True
        elif opt in ("-g", "--debug"):
            bDebug = True
        elif opt in ("-z", "--enablemulticore"):
            enableMultiCoreCheck = False
        elif opt in ("-h", "--gprof"):
            bProfiling = True
        elif opt == "--no-retry":
            g_bRetry = False
        elif opt in ("-p", "--with-polyorb-hi-c"):
            g_bPolyORB_HI_C = True
        elif opt in ("-b", "--with-empty-init"):
            bUseEmptyInitializers = True
        elif opt in ("-r", "--with-coverage"):
            bCoverage = True
        elif opt in ("-j", "--keep-case"):
            bKeepCase = True
        elif opt in ("-o", "--output"):
            outputDir = arg
        elif opt in ("-c", "--deploymentView"):
            depl_aadlFile = arg
        elif opt in ("-i", "--interfaceView"):
            i_aadlFile = arg
        elif opt in ("-w", "--with-cv-attributes"):
            cvAttributesFile = arg
1483
1484
        elif opt in ("-x", "--timer"):
            timerResolution = arg
Maxime Perrotin's avatar
Maxime Perrotin committed
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
        elif opt in ("-n", "--nodeOptions"):
            subName = arg.split('@')[0]
            onOffLookup = {'on': True, 'off': False}
            for o in arg.split('@')[1:]:
                cmd, value = o.split('=')
                if value not in onOffLookup:
                    panic("Value can be '%s', not '%s' (in '%s')" %
                          ("','".join(onOffLookup.keys()), value, arg))
                value = onOffLookup[value]
                if cmd == 'debug':
                    if value:
                        g_customCFlagsPerNode.setdefault(subName, []).append("-g")
                        g_customLDFlagsPerNode.setdefault(subName, []).append("-g")
                    else:
                        g_customCFlagsPerNode.setdefault(subName, []).append("-O -DNDEBUG")
                        g_customLDFlagsPerNode.setdefault(subName, []).append("")
                elif cmd == 'gcov':
                    if value:
                        g_customCFlagsPerNode.setdefault(subName, []).append("-g -fprofile-arcs -ftest-coverage -DCOVERAGE")
                        g_customLDFlagsPerNode.setdefault(subName, []).append("-g  -fprofile-arcs -ftest-coverage -lgcov")
                elif cmd == 'gprof':
                    if value:
                        g_customCFlagsPerNode.setdefault(subName, []).append("-pg")
                        g_customLDFlagsPerNode.setdefault(subName, []).append("-pg")
                elif cmd == 'stackCheck':
                    if value:
                        g_customCFlagsPerNode.setdefault(subName, []).append("-fstack-check -fstack-protector")
                        g_customLDFlagsPerNode.setdefault(subName, []).append("-fstack-check -fstack-protector")
        elif opt in ("-S", "--subSCADE"):
            scadeSubName = arg.split(':')[0]
            if len(arg.split(':')) <= 1:
                panic('SCADE subsystems must be specified in the form subsysAadlName:zipFile')
            scadeSubsystems[scadeSubName] = arg.split(':')[1]
        elif opt in ("-M", "--subSIMULINK"):
            simulinkSubName = arg.split(':')[0]
            if len(arg.split(':')) <= 1:
                panic('SIMULINK subsystems must be specified in the form subsysAadlName:zipFile')
            simulinkSubsystems[simulinkSubName] = arg.split(':')[1]
1523
1524
1525
1526
1527
        elif opt in ("-I", "--subMicroPython"):
            micropythonSubName = arg.split(':')[0]
            if len(arg.split(':')) <= 1:
                panic('MicroPython subsystems must be specified in the form subsysAadlName:zipFile')
            micropythonSubsystems[micropythonSubName] = arg.split(':')[1]
1528
1529
1530
1531
1532
        elif opt in ("-QC", "--subQGenC"):
            qgencSubName = arg.split(':')[0]
            if len(arg.split(':')) <= 1:
                panic('QGenC subsystems must be specified in the form subsysAadlName:zipFile')
            cSubsystems[qgencSubName] = arg.split(':')[1]
Maxime Perrotin's avatar
Maxime Perrotin committed
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
        elif opt in ("-C", "--subC"):
            cSubName = arg.split(':')[0]
            if len(arg.split(':')) <= 1:
                panic('C subsystems must be specified in the form subsysAadlName:zipFile')
            cSubsystems[cSubName] = arg.split(':')[1]
        elif opt in ("-B", "--subCPP"):
            cppSubName = arg.split(':')[0]
            if len(arg.split(':')) <= 1:
                panic('C++ subsystems must be specified in the form subsysAadlName:zipFile')
            cppSubsystems[cppSubName] = arg.split(':')[1]
        elif opt in ("-A", "--subAda"):
            adaSubName = arg.split(':')[0]
            if len(arg.split(':')) <= 1:
                panic('Ada subsystems must be specified in the form subsysAadlName:zipFile')
            adaSubsystems[adaSubName] = arg.split(':')[1]
1548
1549
1550
1551
1552
1553
        elif opt in ("-QA", "--subQGenAda"):
            adaSubName = arg.split(':')[0]
            if len(arg.split(':')) <= 1:
                panic('QGenAda subsystems must be specified in the form subsysAadlName:zipFile')
            qgenadaSubsystems[adaSubName] = arg.split(':')[1]
            adaSubsystems[adaSubName] = arg.split(':')[1]
Maxime Perrotin's avatar
Maxime Perrotin committed
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
        elif opt in ("-G", "--subOG"):
            ogSubName = arg.split(':')[0]
            if len(arg.split(':')) <= 1:
                panic('ObjectGeode subsystems must be specified in the form subsysAadlName:file1.pr<,file2.pr,..>')
            ogSubsystems.setdefault(ogSubName, []).extend(arg.split(':')[1].split(","))
        elif opt in ("-P", "--subRTDS"):
            rtdsSubName = arg.split(':')[0]
            if len(arg.split(':')) <= 1:
                panic('RTDS subsystems must be specified in the form subsysAadlName:zipFile')
            rtdsSubsystems[rtdsSubName] = arg.split(':')[1]
        elif opt in ("-V", "--subVHDL"):
            vhdlSubsystems[arg] = 1
        elif opt in ("-e", "--with-extra-C-code"):
            try:
                partition, extraCdir = arg.split(':')
                if not os.path.exists(extraCdir) or not os.path.isdir(extraCdir):
                    panic("Can't find directory with extra C code: '%s'" % extraCdir)
                extraCdir = os.path.abspath(extraCdir)
                CDirectories.setdefault(partition, []).append(extraCdir)
            except:
                panic("Invalid argument to -e (%s) - must be <deploymentPartition:directoryWithCfiles>" % arg)
        elif opt in ("-d", "--with-extra-Ada-code"):
            try:
                partition, extraADAdir = arg.split(':')
                if not os.path.exists(extraADAdir) or not os.path.isdir(extraADAdir):
                    panic("Can't find directory with extra Ada code: '%s'" % extraADAdir)
                extraADAdir = os.path.abspath(extraADAdir)
                AdaDirectories.setdefault(partition, []).append(extraADAdir)
                if AdaIncludePath is not None:
1583
                    AdaIncludePath += ":" + extraADAdir
Maxime Perrotin's avatar
Maxime Perrotin committed
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
                else:
                    AdaIncludePath = extraADAdir
                os.putenv("ADA_INCLUDE_PATH", AdaIncludePath)
            except:
                panic("Invalid argument to -d (%s) - must be <deploymentPartition:directoryWithADBfiles>" % arg)
        elif opt in ("-l", "--with-extra-lib"):
            try:
                partition, extraLibs = arg.split(":")
                extraLibs = extraLibs.split(",")
                for idx, l in enumerate(extraLibs[:]):
                    if not os.path.exists(l) or not (os.path.isfile(l) or os.path.islink(l)):
                        panic("Can't find file or symlink for library '%s'" % l)
                    extraLibs[idx] = os.path.abspath(l)
                ExtraLibraries.setdefault(partition, []).extend(copy.deepcopy(extraLibs))
            except:
                panic("Invalid argument to -l (%s) - must be: deploymentPartition:/path/to/libLibrary1.a<,/path/to/libLibrary2.a,...>" % arg)

    if outputDir == "" or depl_aadlFile == "" or i_aadlFile == "":
        usage()
    if enableMultiCoreCheck and DetermineNumberOfCPUs() > 1:
        panic("""
VMWARE has timing issues when emulating multi-core CPUs, you MUST change
your .vmx to only use 1 core in this virtual machine. If you intend to use
this machine simply to build a binary - but NOT to run it, then you can
disable this check with the -z command line argument or by setting
"DISABLE_MULTICORE_CHECK" in your environment.
""")

    global g_absOutputDir
    g_absOutputDir = os.path.abspath(outputDir)
    mkdirIfMissing(outputDir)

    # Initial log entry
    mysystem("date", outputDir=g_absOutputDir)

1619
    # Removed check for bash, 2011/Apr/8 : all bashisms are gone now (I think)
1620
1621
    # banner("Checking for valid shell")
    # mysystem("/bin/sh --version 2>/dev/null | grep bash >/dev/null || { echo Your /bin/sh is not bash ... aborting... ; exit 1 ; }")
1622

Maxime Perrotin's avatar
Maxime Perrotin committed
1623
1624
1625
1626
1627
1628
1629
    filesMustExist = [depl_aadlFile, i_aadlFile]
    if cvAttributesFile != "":
        filesMustExist.append(cvAttributesFile)
    for f in filesMustExist:
        if not os.path.exists(f):
            panic("'%s' doesn't exist!" % f)

1630
    os.putenv("ASN1SCC", getSingleLineFromCmdOutput("echo $DMT").strip() + "/asn1scc/asn1.exe")
Maxime Perrotin's avatar
Maxime Perrotin committed
1631

1632
1633