taste_orchestrator.py 113 KB
Newer Older
Maxime Perrotin's avatar
Maxime Perrotin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
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
103
104
105
106
107
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
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
250
251
252
253
254
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
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
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
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
570
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
604
605
606
607
608
609
610
611
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
639
640
641
642
643
644
645
646
647
648
649
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
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
725
726
727
728
729
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
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
826
827
828
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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# (C) Semantix Information Technologies.
# 
# Copyright 2014-2015 IB Krates <info@krates.ee>
#       QGenc code generator integration
#
# Semantix Information Technologies is licensing the code of the
# Data Modelling Tools (DMT) in the following dual-license mode:
#
# Commercial Developer License:
#       The DMT Commercial Developer License is the appropriate version
# to use for the development of proprietary and/or commercial software.
# This version is for developers/companies who do not want to share
# the source code they develop with others or otherwise comply with the
# terms of the GNU Lesser General Public License version 3
#
# GNU LGPL v.3
#       This version of DMT is the one to use for the development of
# non-commercial applications, when you are willing to comply
# with the terms of the GNU Lesser General Public License version 3
#
# The features of the two licenses are summarized below:
#
#                       Commercial
#                       Developer               LGPL
#                       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
# proprietary           no source code needs    to the LGPL and all source code
# 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

__version__ = "1.0.0"

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

# 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)

    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)
    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
        os.system('env > "' + g_absOutputDir + os.sep + 'env.txt"')
        if g_bRetry:
            if os.getenv('CLEANUP') is not None:
                print "Exception in user code:"
                print '-'*60
                traceback.print_stack()
                print '-'*60
            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()
        if None != f.close():
            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():
        print "\n"+chr(27)+"[32m" + msg + chr(27) + "[0m\n"
    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'''
    panic("TASTE Orchestrator\n"
          "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"
          "-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"
          "-w, --with-cv-attributes properties_filename\n\tUpdate thread priorities, stack size and offset/phase during the build")


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 "
    if kind.startswith("PLATFORM_LEON_RTEMS"):
        result += " -msoft-float "
    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
    for d in os.listdir(polyorbActivityHpath):
        if os.path.isdir(polyorbActivityHpath + os.sep + d) and d.startswith(functionName):
            polyorbActivityHpath += os.sep + d
            break
    else:
        # No such directory found under deployment...
        # Check the 'nodes' info to see who is using this
        for partition in g_distributionNodes.keys():
            if functionName.lower() in [x.lower() for x in g_distributionNodes[partition]]:
                polyorbActivityHpath += os.sep + partition
                break
        else:
            polyorbActivityHpath = ""

    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]
    result = " " + mflags(node) + " "
    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 "
    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.
    #if "-pg" not in result and not any(map(lambda x: x in kind, ["LEON", "COMPCERT"])):
    #   result += " -fdata-sections -ffunction-sections "
    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]:
            extraCdirIncludes += "-I \""+d + "\" "
    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)


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)
        #mysystem("cp ../../GlueAndBuild/glue%s/asn1_types.ads ." % baseDir)
        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
        #mysystem("\"$GNATGCC\" -g -c *.adb")
        #mysystem("for i in *.ads ; do [ ! -f ${i/.ads/.adb} ] && \"$GNATGCC\" -g -c *.ads || break ; done")
        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("..")
        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]:
                extraCdirIncludes += "-I \""+d + "\" "
        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" %
                 (cflagsSoFar+extraCdirIncludes+CalculateCFLAGS(ss)+CalculateUserCodeOnlyCFLAGS(ss), ss))
        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]:
                extraCdirIncludes += "-I \""+d + "\" "
        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" %
                 (cflagsSoFar+CalculateCFLAGS(baseDir)+CalculateUserCodeOnlyCFLAGS(baseDir), extraCdirIncludes, baseDir))
        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]:
                extraCdirIncludes += "-I \""+d + "\" "
        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" %
                     (cflagsSoFar+CalculateCFLAGS(baseDir)+CalculateUserCodeOnlyCFLAGS(baseDir), extraCdirIncludes, baseDir))
        os.chdir("..")


def BuildGUIs(guiSubsystems, cflagsSoFar, asn1Grammar):
    '''Builds automatically generated GUIs'''
    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
        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"))
        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])
        mysystem("cat Makefile | sed 's,applicationName,%s,g' > a_temp_name && mv a_temp_name Makefile" % (baseDir+"_GUI"))
        mysystem("cp -u ../../GlueAndBuild/glue" + baseDir + "/C_*.[ch] .")
        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()))
        if not os.path.exists(baseDir + os.sep + "PythonAccess.i"):
            panic("Python generated code did not contain a %s ..." % (baseDir+os.sep+"PythonAccess.i"))
        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")
        mysystem("\"$ASN2DATAMODEL\" -o asn2dataModel -toPython " + os.path.basename(asn1Grammar))
        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))
        mysystem("make -f Makefile.python taste")
        os.chdir("..")
        mysystem("cp asn2dataModel/asn1crt.h asn2dataModel/Stubs.py asn2dataModel/DV.py asn2dataModel/_DV.* .")
        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("-", "_"))
        mysystem("swig  -Wall -includeall -outdir . -python ./PythonAccess.i")
        mysystem("gcc -g -fPIC -c `python-config --cflags` gui_swig.c queue_manager.c timeInMS.c debug_messages.c PythonAccess_wrap.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")
        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("..")


def RenameCommonlyNamedSymbols(scadeSubsystems, simulinkSubsystems, cSubsystems, cppSubsystems, adaSubsystems, rtdsSubsystems, ogSubsystems, guiSubsystems, cyclicSubsystems, vhdlSubsystems):
    '''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 = {}
    for baseDir in scadeSubsystems.keys() + simulinkSubsystems.keys() + cSubsystems.keys() + cppSubsystems.keys() + \
            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)
        if 0 != len([x for x in os.listdir("GlueAndBuild/glue"+baseDir) if x.endswith(".o")]):
            mysystem("mv GlueAndBuild/glue"+baseDir+"/*.o " + baseDir + appendTarget)

    for prefix, systemPlatform in prefixes.items():
        renamingDirs = 0
        cmd = "taste-patch-aplc "
        for baseDir in scadeSubsystems.keys() + simulinkSubsystems.keys() + cSubsystems.keys() + cppSubsystems.keys() + \
                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:
            os.putenv("OBJCOPY", prefix+"objcopy")
            asn1SccFolder = "auto-src_" + systemPlatform
            if os.path.isdir(asn1SccFolder):
                cmd += ' ' + asn1SccFolder + "/"
                cmd += ' ' + asn1SccFolder
            mysystem(cmd)


def InvokeOcarinaMakefiles(
    scadeSubsystems, simulinkSubsystems, cSubsystems, cppSubsystems, adaSubsystems, rtdsSubsystems, ogSubsystems, guiSubsystems, cyclicSubsystems, vhdlSubsystems,
        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:]
            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 ""

            # 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 = ""
            # 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] .")
                mysystem("\"$GNATGCC\" -c %s *.c" % (cflagsSoFar+CalculateCFLAGS(node)+CalculateUserCodeOnlyCFLAGS(node)))
                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()
                #open("conf.ec",'w').write("pragma No_Run_Time;\n")
                #mysystem("gnatmake -c -I../../auto-src " + baseDir + " " + x + " -gnatec=conf.ec")
                mysystem("\"$GNATMAKE\" -c %s -I. tasteada.ads" % mflags(node))
                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 ""
                mysystem("\"$GNATMAKE\" -c %s %s ada-start.adb" % (dbg, mflags(node)))
                for line in open("ada-start.adb").readlines():
                    if -1 != line.find("adalib"):
                        poHiAdaLinkCmd = line.strip().replace ("--", "")
                        runtimePath = " " + line.strip().replace("-L", "-Wl,-R") + " "
                        poHiAdaLinkCmd += runtimePath.replace ("--", "")
                if poHiAdaLinkCmd == "":
                    panic("There was no line containing 'adalib' inside 'ada-start.adb'")
                poHiAdaLinkCmd += " -lgnat -lgnarl"
                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]:
                for baseDir in scadeSubsystems.keys() + simulinkSubsystems.keys() + cSubsystems.keys() + cppSubsystems.keys() + adaSubsystems.keys() + rtdsSubsystems.keys():
                    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: