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
8
#
# (C) Semantix Information Technologies.
#
9
10
11
# Copyright 2014-2015 IB Krates <info@krates.ee>
#       QGenc code generator integration
#
Maxime Perrotin's avatar
Maxime Perrotin committed
12
13
14
# Semantix Information Technologies is licensing the code of the
# Data Modelling Tools (DMT) in the following dual-license mode:
#
15
# GNU GPL v. 2.1:
Maxime Perrotin's avatar
Maxime Perrotin committed
16
17
#       This version of DMT is the one to use for the development of
# non-commercial applications, when you are willing to comply
18
# with the terms of the GNU General Public License version 2.1.
Maxime Perrotin's avatar
Maxime Perrotin committed
19
20
21
22
#
# The features of the two licenses are summarized below:
#
#                       Commercial
23
#                       Developer               GPL
Maxime Perrotin's avatar
Maxime Perrotin committed
24
25
26
27
28
29
30
31
32
#                       License
#
# License cost          License fee charged     No license fee
#
# Must provide source
# code changes to DMT   No, modifications can   Yes, all source code
#                       be closed               must be provided back
#
# Can create            Yes, That is,           No, applications are subject
33
# proprietary           no source code needs    to the GPL and all source code
Maxime Perrotin's avatar
Maxime Perrotin committed
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# applications          to be disclosed         must be made available
#
# Support               Yes, 12 months of       No, but available separately
#                       premium technical       for purchase
#                       support
#
# Charge for Runtimes   None                    None
#
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

# 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 = {}

103
104
105
106
107
# 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# 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)

139
140
141
142
143
    @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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
    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)
168
169
    if g_absOutputDir != "":
        os.system('env > "' + g_absOutputDir + os.sep + 'env.txt"')
Maxime Perrotin's avatar
Maxime Perrotin committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
    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
184
185
        if g_absOutputDir != "":
            os.system('env > "' + g_absOutputDir + os.sep + 'env.txt"')
Maxime Perrotin's avatar
Maxime Perrotin committed
186
187
188
        if g_bRetry:
            if os.getenv('CLEANUP') is not None:
                print "Exception in user code:"
189
                print '-' * 60
Maxime Perrotin's avatar
Maxime Perrotin committed
190
                traceback.print_stack()
191
                print '-' * 60
Maxime Perrotin's avatar
Maxime Perrotin committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
            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()
207
        if f.close() is not None:
Maxime Perrotin's avatar
Maxime Perrotin committed
208
209
210
211
212
213
214
215
216
217
            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():
218
        print "\n" + chr(27) + "[32m" + msg + chr(27) + "[0m\n"
Maxime Perrotin's avatar
Maxime Perrotin committed
219
220
221
222
223
224
225
226
227
228
    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'''
229
    panic("TASTE/ASSERT orchestrator, revision: COMMITID\n"
Maxime Perrotin's avatar
Maxime Perrotin committed
230
231
232
233
234
235
236
237
238
239
240
241
          "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"
          "-s, --stack stackSizeInKB\n\tHow much stack size to use (in KB)\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"
242
          "-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
243
244
245
246
247
248
249
250
251
252
          "-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"
253
254
          "-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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279


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 "
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
    # 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 "
    #
295
    if kind.startswith("PLATFORM_GNAT_RUNTIME"):
296
        result += " -mfloat-abi=hard "
297
298
        # Cortex M4's FPU does not support double precision! if C code uses double,
        # it must be forced to use float instead:
299
300
        # Edit: this worked in gnat2016 but not in gnat2017
        # result += " -fshort-double "
Maxime Perrotin's avatar
Maxime Perrotin committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
    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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
    # 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
354
355
            break
    else:
356
        polyorbActivityHpath = ""
Maxime Perrotin's avatar
Maxime Perrotin committed
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372

    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]
373
    result = " -std=c99 " + mflags(node) + " "
Maxime Perrotin's avatar
Maxime Perrotin committed
374
375
376
377
378
379
380
381
382
    if g_bPolyORB_HI_C and withPOHIC:
        result += handlePoHiC(node) + " "
    result += handleXenomaiCflags(node)
    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 "
383
    if "GNAT_RUNTIME" in kind:
384
385
        result += " -DNDEBUG "  # Not supported by AdaCore's CertyFlie...

Maxime Perrotin's avatar
Maxime Perrotin committed
386
387
388
389
390
391
392
393
    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.
394
395
    # 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
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
526
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
558
559
560
561
562
563
564
565
566
567
568
569
    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:
        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])
    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]
    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:
                        opt = findCO.group(1)
                        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]:
570
            extraCdirIncludes += "-I \"" + d + "\" "
Maxime Perrotin's avatar
Maxime Perrotin committed
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
    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)


604
605
606
607
608
609
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():

610
        mpySource = "$(taste-config --prefix)/../tool-src/upython-taste"
611
        mpyTemplDir = mpySource + "/ports/esa-taste"
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
        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))
            f.write("const unsigned char mpy_script_data[%u] = \""  % len(mpy_data))
            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")
            f.write("extern const unsigned char mpy_script_data[%u];\n"  % len(mpy_data))

        # copy the MicroPython source
        mysystem("for file in %s/py/*.c; do cp $file ./py_$(basename $file); done" % (mpySource,))
        mkdirIfMissing("py");
        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
639
640
641
        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,))
642
643
644
645
646
647
648
649
650
651
652
653
654
655
        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("../..")

656
657
658
        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)))
659
660


Maxime Perrotin's avatar
Maxime Perrotin committed
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
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)
693
        # mysystem("cp ../../GlueAndBuild/glue%s/asn1_types.ads ." % baseDir)
Maxime Perrotin's avatar
Maxime Perrotin committed
694
695
696
697
698
699
700
701
702
        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
703
704
        # 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
705
706
707
        if (baseDir in g_distributionNodesPlatform.keys()):
            UpdateEnvForNode(baseDir)
        mysystem("\"$GNATGCC\" -c %s -I ../../GlueAndBuild/glue%s/ -I ../../auto-src/ *.c" %
708
                 (cflagsSoFar + CalculateCFLAGS(baseDir) + CalculateUserCodeOnlyCFLAGS(baseDir), baseDir))
Maxime Perrotin's avatar
Maxime Perrotin committed
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
        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]:
736
                extraCdirIncludes += "-I \"" + d + "\" "
Maxime Perrotin's avatar
Maxime Perrotin committed
737
738
739
        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" %
740
                 (cflagsSoFar + extraCdirIncludes + CalculateCFLAGS(ss) + CalculateUserCodeOnlyCFLAGS(ss), ss))
Maxime Perrotin's avatar
Maxime Perrotin committed
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
        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]:
766
                extraCdirIncludes += "-I \"" + d + "\" "
Maxime Perrotin's avatar
Maxime Perrotin committed
767
768
769
        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" %
770
                 (cflagsSoFar + CalculateCFLAGS(baseDir) + CalculateUserCodeOnlyCFLAGS(baseDir), extraCdirIncludes, baseDir))
Maxime Perrotin's avatar
Maxime Perrotin committed
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
        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]:
786
                extraCdirIncludes += "-I \"" + d + "\" "
Maxime Perrotin's avatar
Maxime Perrotin committed
787
788
789
790
        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" %
791
                     (cflagsSoFar + CalculateCFLAGS(baseDir) + CalculateUserCodeOnlyCFLAGS(baseDir), extraCdirIncludes, baseDir))
Maxime Perrotin's avatar
Maxime Perrotin committed
792
793
794
795
        os.chdir("..")


def BuildGUIs(guiSubsystems, cflagsSoFar, asn1Grammar):
796
    '''Builds automatically generated wxWdigets GUIs'''
Maxime Perrotin's avatar
Maxime Perrotin committed
797
798
799
800
801
802
803
    if guiSubsystems:
        g_stageLog.info("Building automatically created GUIs")
    commentedGUIfilters = []
    for baseDir in guiSubsystems:
        if not os.path.isdir(baseDir):
            panic("No directory %s! (pwd=%s)" % (baseDir, os.getcwd()))
        # This is for GUI code
804
805
        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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
        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])
838
        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
839
        mysystem("cp -u ../../GlueAndBuild/glue" + baseDir + "/C_*.[ch] .")
840
        # mysystem("cp ../auto-src/* .")
Maxime Perrotin's avatar
Maxime Perrotin committed
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
        if baseDir.endswith('probe_console'):
            os.chdir("../..")
            continue
        os.chdir("../..")
    return commentedGUIfilters


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")
870
        mysystem("asn2dataModel -o asn2dataModel -toPython " + os.path.basename(asn1Grammar))
Maxime Perrotin's avatar
Maxime Perrotin committed
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
        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))
887
        mysystem("make -f Makefile.python")
Maxime Perrotin's avatar
Maxime Perrotin committed
888
        os.chdir("..")
889
        mysystem("cp asn2dataModel/asn1crt.h asn2dataModel/Stubs.py asn2dataModel/DV* asn2dataModel/*.so .")
Maxime Perrotin's avatar
Maxime Perrotin committed
890
891
        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("-", "_"))
892
893
894
895
896
        # 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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
        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("..")


917
def RenameCommonlyNamedSymbols(scadeSubsystems, simulinkSubsystems, micropythonSubsystems, cSubsystems, cppSubsystems, adaSubsystems, rtdsSubsystems, ogSubsystems, guiSubsystems, cyclicSubsystems, vhdlSubsystems):
Maxime Perrotin's avatar
Maxime Perrotin committed
918
919
920
921
922
923
924
925
926
927
928
929
    '''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 = {}
930
    for baseDir in scadeSubsystems.keys() + simulinkSubsystems.keys() + micropythonSubsystems.keys() + cSubsystems.keys() + cppSubsystems.keys() + \
Maxime Perrotin's avatar
Maxime Perrotin committed
931
932
933
934
935
936
937
            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)
938
939
        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
940
941
942

    for prefix, systemPlatform in prefixes.items():
        renamingDirs = 0
943
        cmd = "patchAPLCs.py "
944
        for baseDir in scadeSubsystems.keys() + simulinkSubsystems.keys() + micropythonSubsystems.keys() + cSubsystems.keys() + cppSubsystems.keys() + \
Maxime Perrotin's avatar
Maxime Perrotin committed
945
946
947
948
949
950
951
952
953
954
955
956
957
958
                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:
959
            os.putenv("OBJCOPY", prefix + "objcopy")
Maxime Perrotin's avatar
Maxime Perrotin committed
960
961
962
963
964
965
966
967
            asn1SccFolder = "auto-src_" + systemPlatform
            if os.path.isdir(asn1SccFolder):
                cmd += ' ' + asn1SccFolder + "/"
                cmd += ' ' + asn1SccFolder
            mysystem(cmd)


def InvokeOcarinaMakefiles(
968
    scadeSubsystems, simulinkSubsystems, micropythonSubsystems, cSubsystems, cppSubsystems, adaSubsystems, rtdsSubsystems, ogSubsystems, guiSubsystems, cyclicSubsystems, vhdlSubsystems,
Maxime Perrotin's avatar
Maxime Perrotin committed
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
        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:]
984
985
986
            if node == "":
                # Handle LaTEX-doxygen related Makefiles (closes: #488)
                continue
Maxime Perrotin's avatar
Maxime Perrotin committed
987
988
989
990
991
992
993
994
995
996
            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 ""

997
998
999
1000
            # VCD support
            if bDebug and g_bPolyORB_HI_C:
                userCFlags += "-D__PO_HI_USE_VCD=1 "

For faster browsing, not all history is shown. View entire blame