-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbuild.sh
More file actions
executable file
·1000 lines (857 loc) · 29.6 KB
/
build.sh
File metadata and controls
executable file
·1000 lines (857 loc) · 29.6 KB
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 bash
#
# [=========================================================================]
# OpenAA: Open Source Adaptive AUTOSAR Project
# Author: Sherif Mohamed
#
# File description:
# -----------------
# logging, security hardening, cross-platform support, and modular design.
#
# Features:
# - Strict mode with comprehensive error handling
# - Advanced logging with multiple outputs and JSON support
# - Security hardening with input validation
# - Cross-platform compatibility
# - Parallel build support with resource monitoring
# - Modular architecture with clear separation of concerns
# - Support for batch builds (all targets/configurations)
#
# Usage:
# ./build.sh [options]
# ./build.sh --all-targets --all-configs --qnx710-sdp /path/to/qnx710 --qnx800-sdp /path/to/qnx800
# ./build.sh --clean --build-type Release --build-target qcc12_qnx800_aarch64 \
# --qnx800-sdp /root/qnx800/qnxsdp-env.sh --exception-safety safe --jobs 16
# [=========================================================================]
# ------------------------------------------------------------------------------
# 1) Strict Mode and Safety Settings
# ------------------------------------------------------------------------------
set -euo pipefail
IFS=$'\n\t'
# Enable extended debugging features
shopt -s extdebug
shopt -s inherit_errexit
shopt -s nullglob
# Script metadata
readonly SCRIPT_NAME="$(basename "${BASH_SOURCE[0]}")"
readonly BUILD_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_VERSION="2.0.0"
readonly SCRIPT_PID="$$"
# ------------------------------------------------------------------------------
# 2) Global Constants and Configuration
# ------------------------------------------------------------------------------
readonly BUILD_TYPES=("Debug" "Release")
readonly SUPPORTED_TARGETS=(
"gcc11_linux_x86_64"
"gcc11_linux_aarch64"
"gcc13_linux_x86_64"
"gcc13_linux_aarch64"
"clang21_linux_x86_64"
"clang21_linux_aarch64"
"qcc8_qnx710_aarch64"
"qcc8_qnx710_x86_64"
"qcc12_qnx800_aarch64"
"qcc12_qnx800_x86_64"
)
# QNX target patterns for environment detection
readonly QNX710_PATTERN="qcc8_qnx710_"
readonly QNX800_PATTERN="qcc12_qnx800_"
# Exit codes
readonly EXIT_SUCCESS=0
readonly EXIT_GENERAL_ERROR=1
readonly EXIT_MISUSE=2
readonly EXIT_CANNOT_EXECUTE=126
readonly EXIT_COMMAND_NOT_FOUND=127
readonly EXIT_INVALID_ARGUMENT=128
readonly EXIT_SIGNAL_BASE=128
# ------------------------------------------------------------------------------
# 3) Default Build Options
# ------------------------------------------------------------------------------
BUILD_TYPE="Release"
BUILD_TARGET="gcc11_linux_x86_64"
NUM_JOBS=""
CLEAN_BUILD=false
QNX710_SDP_PATH=""
QNX800_SDP_PATH=""
EXCEPTION_SAFETY_MODE="conditional"
ALL_TARGETS=false
ALL_CONFIGS=false
VERBOSE=false
DRY_RUN=false
LOG_LEVEL="INFO"
LOG_FILE=""
LOG_JSON=false
# Performance monitoring
BUILD_START_TIME=""
BUILD_END_TIME=""
# ------------------------------------------------------------------------------
# 4) Advanced Logging System
# ------------------------------------------------------------------------------
# ANSI color codes
readonly COLOR_RED='\033[0;31m'
readonly COLOR_GREEN='\033[0;32m'
readonly COLOR_YELLOW='\033[0;33m'
readonly COLOR_BLUE='\033[0;34m'
readonly COLOR_MAGENTA='\033[0;35m'
readonly COLOR_CYAN='\033[0;36m'
readonly COLOR_WHITE='\033[0;37m'
readonly COLOR_RESET='\033[0m'
# Log levels
declare -A LOG_LEVELS=(
["TRACE"]=0
["DEBUG"]=1
["INFO"]=2
["WARN"]=3
["ERROR"]=4
["FATAL"]=5
)
# Initialize logging
init_logging() {
# Create log directory if logging to file
if [[ -n "$LOG_FILE" ]]; then
local log_dir
log_dir="$(dirname "$LOG_FILE")"
mkdir -p "$log_dir"
# Initialize log file with header
{
echo "# OpenAA Build Script Log"
echo "# Version: $SCRIPT_VERSION"
echo "# Started: $(date -u +"%Y-%m-%dT%H:%M:%SZ")"
echo "# PID: $SCRIPT_PID"
echo "# Command: $0 $*"
echo "# ========================"
} > "$LOG_FILE"
fi
}
# Enhanced logging function with multiple outputs
log() {
local level="${1:-INFO}"
local message="${2:-}"
local timestamp
timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
# Check if we should log this level
if [[ ${LOG_LEVELS[$level]:-2} -lt ${LOG_LEVELS[$LOG_LEVEL]:-2} ]]; then
return 0
fi
# Console output with colors
local color=""
case "$level" in
TRACE) color="$COLOR_WHITE" ;;
DEBUG) color="$COLOR_CYAN" ;;
INFO) color="$COLOR_GREEN" ;;
WARN) color="$COLOR_YELLOW" ;;
ERROR) color="$COLOR_RED" ;;
FATAL) color="$COLOR_MAGENTA" ;;
esac
# Format console message
if [[ -t 1 ]] && [[ -z "${NO_COLOR:-}" ]]; then
printf "${color}[%-5s]${COLOR_RESET} [%s] %s: %s\n" \
"$level" "$timestamp" "$SCRIPT_NAME" "$message" >&2
else
printf "[%-5s] [%s] %s: %s\n" \
"$level" "$timestamp" "$SCRIPT_NAME" "$message" >&2
fi
# File output
if [[ -n "$LOG_FILE" ]]; then
if [[ "$LOG_JSON" == "true" ]]; then
# JSON format for structured logging
printf '{"timestamp":"%s","level":"%s","script":"%s","pid":%d,"message":"%s"}\n' \
"$timestamp" "$level" "$SCRIPT_NAME" "$SCRIPT_PID" \
"$(echo "$message" | sed 's/"/\\"/g')" >> "$LOG_FILE"
else
printf "[%-5s] [%s] %s[%d]: %s\n" \
"$level" "$timestamp" "$SCRIPT_NAME" "$SCRIPT_PID" "$message" >> "$LOG_FILE"
fi
fi
# Fatal errors trigger immediate exit
if [[ "$level" == "FATAL" ]]; then
exit "$EXIT_GENERAL_ERROR"
fi
}
# ------------------------------------------------------------------------------
# 5) Input Validation and Security
# ------------------------------------------------------------------------------
# Validate string contains only safe characters
validate_safe_string() {
local input="$1"
local pattern="${2:-^[a-zA-Z0-9._/-]+$}"
local name="${3:-input}"
if [[ ! "$input" =~ $pattern ]]; then
log ERROR "Invalid $name: '$input' contains unsafe characters"
return "$EXIT_INVALID_ARGUMENT"
fi
return 0
}
# Validate numeric input
validate_number() {
local input="$1"
local min="${2:-1}"
local max="${3:-9999}"
local name="${4:-number}"
if [[ ! "$input" =~ ^[0-9]+$ ]]; then
log ERROR "Invalid $name: '$input' is not a number"
return "$EXIT_INVALID_ARGUMENT"
fi
if [[ "$input" -lt "$min" ]] || [[ "$input" -gt "$max" ]]; then
log ERROR "Invalid $name: '$input' is outside valid range [$min-$max]"
return "$EXIT_INVALID_ARGUMENT"
fi
return 0
}
# Validate file exists and is readable
validate_file() {
local file="$1"
local name="${2:-file}"
if [[ ! -f "$file" ]]; then
log ERROR "$name does not exist: $file"
return "$EXIT_INVALID_ARGUMENT"
fi
if [[ ! -r "$file" ]]; then
log ERROR "$name is not readable: $file"
return "$EXIT_INVALID_ARGUMENT"
fi
return 0
}
# Validate build target
validate_build_target() {
local target="$1"
local valid=false
for valid_target in "${SUPPORTED_TARGETS[@]}"; do
if [[ "$target" == "$valid_target" ]]; then
valid=true
break
fi
done
if [[ "$valid" != "true" ]]; then
log ERROR "Invalid build target: $target"
log ERROR "Supported targets: ${SUPPORTED_TARGETS[*]}"
return "$EXIT_INVALID_ARGUMENT"
fi
return 0
}
# ------------------------------------------------------------------------------
# 6) System Detection and Dependency Checking
# ------------------------------------------------------------------------------
# Detect operating system
detect_os() {
local os=""
if [[ -f /etc/os-release ]]; then
# shellcheck disable=SC1091
source /etc/os-release
os="${ID:-unknown}"
elif [[ "$OSTYPE" == "darwin"* ]]; then
os="macos"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
os="linux"
else
os="unknown"
fi
echo "$os"
}
# Check for required commands
check_dependencies() {
local deps=("cmake" "git" "make")
local missing=()
for cmd in "${deps[@]}"; do
if ! command -v "$cmd" &>/dev/null; then
missing+=("$cmd")
fi
done
if [[ ${#missing[@]} -gt 0 ]]; then
log FATAL "Missing required dependencies: ${missing[*]}"
fi
# Check cmake version
local cmake_version
cmake_version=$(cmake --version | head -1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')
log DEBUG "Found CMake version: $cmake_version"
}
# Get number of available CPU cores
get_cpu_count() {
local cpu_count
if command -v nproc &>/dev/null; then
cpu_count=$(nproc)
elif command -v sysctl &>/dev/null; then
cpu_count=$(sysctl -n hw.ncpu 2>/dev/null || echo 1)
else
cpu_count=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || echo 1)
fi
echo "$cpu_count"
}
# ------------------------------------------------------------------------------
# 7) Signal Handling and Cleanup
# ------------------------------------------------------------------------------
# Cleanup function for graceful shutdown
cleanup() {
local exit_code=$?
# Log cleanup start
log DEBUG "Starting cleanup (exit code: $exit_code)"
# Kill any background jobs
local jobs
jobs=$(jobs -p)
if [[ -n "$jobs" ]]; then
log WARN "Terminating background jobs: $jobs"
# shellcheck disable=SC2086
kill -TERM $jobs 2>/dev/null || true
sleep 1
# shellcheck disable=SC2086
kill -KILL $jobs 2>/dev/null || true
fi
# Remove temporary files
if [[ -n "${TEMP_DIR:-}" ]] && [[ -d "$TEMP_DIR" ]]; then
log DEBUG "Removing temporary directory: $TEMP_DIR"
rm -rf "$TEMP_DIR"
fi
# Calculate build duration if applicable
if [[ -n "$BUILD_START_TIME" ]] && [[ -n "$BUILD_END_TIME" ]]; then
local duration=$((BUILD_END_TIME - BUILD_START_TIME))
log INFO "Total build time: $(format_duration "$duration")"
fi
# Final log message
if [[ $exit_code -eq 0 ]]; then
log INFO "Script completed successfully"
else
log ERROR "Script failed with exit code: $exit_code"
fi
exit "$exit_code"
}
# Signal handlers
handle_signal() {
local signal="$1"
log WARN "Received signal: $signal"
BUILD_END_TIME=$(date +%s)
exit $((EXIT_SIGNAL_BASE + signal))
}
# Setup signal traps
setup_signals() {
trap cleanup EXIT
trap 'handle_signal 1' HUP
trap 'handle_signal 2' INT
trap 'handle_signal 3' QUIT
trap 'handle_signal 15' TERM
}
# ------------------------------------------------------------------------------
# 8) Utility Functions
# ------------------------------------------------------------------------------
# Format duration in human-readable format
format_duration() {
local seconds="$1"
local hours=$((seconds / 3600))
local minutes=$(((seconds % 3600) / 60))
local secs=$((seconds % 60))
if [[ $hours -gt 0 ]]; then
printf "%dh %dm %ds" "$hours" "$minutes" "$secs"
elif [[ $minutes -gt 0 ]]; then
printf "%dm %ds" "$minutes" "$secs"
else
printf "%ds" "$secs"
fi
}
_capture_to_log_until() {
local _lvl="$1" ; shift
local _stop="$1" ; shift
local _logging=1
while IFS='' read -r _line; do
if ((_logging)); then
log "${_lvl}" "${_line}"
[[ "${_line}" == *"${_stop}"* ]] && _logging=0 # flip the switch
else
printf '%s\n' "${_line}" # plain pass-through
fi
done
}
_exec_and_log_until() {
local _lvl="$1" ; local _stop="$2" ; shift 2
"${@}" 2>&1 | _capture_to_log_until "${_lvl}" "${_stop}"
return ${PIPESTATUS[0]}
}
# Run command with error checking and timing
run_command() {
local stop_pattern=""
if [[ "$1" == --until=* ]]; then
stop_pattern="${1#--until=}"
shift
fi
local cmd=("$@")
local start_time end_time duration status
if [[ "$DRY_RUN" == "true" ]]; then
log INFO "[DRY RUN] Would execute: ${cmd[*]}"
return 0
fi
log DEBUG "Executing: ${cmd[*]}"
start_time=$(date +%s)
if [[ -n "$stop_pattern" ]]; then
_exec_and_log_until DEBUG "$stop_pattern" "${cmd[@]}"
status=$?
elif [[ "$VERBOSE" == "true" ]]; then
"${cmd[@]}"
status=$?
else
"${cmd[@]}" &>/dev/null
status=$?
fi
end_time=$(date +%s)
duration=$((end_time - start_time))
if [[ $status -eq 0 ]]; then
log DEBUG "Command completed in $(format_duration "$duration")"
else
log ERROR "Command failed with exit code $status after $(format_duration "$duration")"
log ERROR "Failed command: ${cmd[*]}"
return $status
fi
return 0
}
# Create directory with proper permissions
create_directory() {
local dir="$1"
local mode="${2:-755}"
if [[ ! -d "$dir" ]]; then
log DEBUG "Creating directory: $dir"
mkdir -p "$dir"
chmod "$mode" "$dir"
fi
}
# ------------------------------------------------------------------------------
# 9) QNX Environment Management
# ------------------------------------------------------------------------------
_capture_to_log() {
local _lvl="$1" ; shift
while IFS='' read -r _line; do
# Skip empty lines to reduce noise — remove this if you really want them
[[ -n "$_line" ]] && log "${_lvl}" "${_line}"
done
}
# Wrapper that keeps the real exit-status of a piped command (PIPESTATUS[0])
_exec_and_log() {
# first arg is log-level, rest is the command
local _lvl="$1"; shift
"${@}" 2>&1 | _capture_to_log "${_lvl}"
return ${PIPESTATUS[0]}
}
# Capture output to log file with logging level
source_with_logging() {
local _lvl="$1" ; shift
local _script="$1" ; shift # keep a clean variable name
# shellcheck disable=SC1090
{ source "${_script}" "$@"; } \
> >(_capture_to_log "${_lvl}") 2>&1
}
# Setup QNX environment based on target
setup_qnx_environment() {
local target="$1"
local sdp_path=""
# Determine which QNX version based on target
if [[ "$target" =~ $QNX710_PATTERN ]]; then
sdp_path="$QNX710_SDP_PATH"
if [[ -z "$sdp_path" ]]; then
log ERROR "QNX 7.10 SDP path required for target: $target"
log ERROR "Use --qnx710-sdp option to specify the path"
return "$EXIT_INVALID_ARGUMENT"
fi
log INFO "Setting up QNX 7.10 environment for target: $target"
elif [[ "$target" =~ $QNX800_PATTERN ]]; then
sdp_path="$QNX800_SDP_PATH"
if [[ -z "$sdp_path" ]]; then
log ERROR "QNX 8.0 SDP path required for target: $target"
log ERROR "Use --qnx800-sdp option to specify the path"
return "$EXIT_INVALID_ARGUMENT"
fi
log INFO "Setting up QNX 8.0 environment for target: $target"
else
# Not a QNX target, nothing to do
return 0
fi
# Validate SDP script exists
if ! validate_file "$sdp_path/qnxsdp-env.sh" "QNX SDP script"; then
return "$EXIT_INVALID_ARGUMENT"
fi
# Source the SDP environment
log DEBUG "Sourcing QNX SDP: $sdp_path/qnxsdp-env.sh"
# shellcheck disable=SC1090
source_with_logging INFO "$sdp_path/qnxsdp-env.sh"
# Verify QNX environment is properly set
if [[ -z "${QNX_HOST:-}" ]] || [[ -z "${QNX_TARGET:-}" ]]; then
log ERROR "QNX environment not properly configured after sourcing SDP"
log ERROR "QNX_HOST: ${QNX_HOST:-not set}"
log ERROR "QNX_TARGET: ${QNX_TARGET:-not set}"
return "$EXIT_GENERAL_ERROR"
fi
log DEBUG "QNX environment configured:"
log DEBUG " QNX_HOST: $QNX_HOST"
log DEBUG " QNX_TARGET: $QNX_TARGET"
return 0
}
# ------------------------------------------------------------------------------
# 10) Build Configuration Management
# ------------------------------------------------------------------------------
# Generate preset name from target and build type
get_preset_name() {
local target="$1"
local build_type="$2"
local preset_name=""
if [[ "$build_type" == "Debug" ]]; then
preset_name="${target}_debug"
else
preset_name="${target}_release"
fi
echo "$preset_name"
}
# Get configuration file path
get_config_file() {
local preset_name="$1"
echo "CMake/CMakeConfig/${preset_name}.cmake"
}
# ------------------------------------------------------------------------------
# 11) Build Operations
# ------------------------------------------------------------------------------
# Clean build directories
clean_build() {
local preset_name="$1"
local build_dir="$BUILD_SCRIPT_DIR/build/$preset_name"
local install_dir="$BUILD_SCRIPT_DIR/install/$preset_name"
if [[ -d "$build_dir" ]]; then
log INFO "Removing build directory: $build_dir"
rm -rf "$build_dir"
fi
if [[ -d "$install_dir" ]]; then
log INFO "Removing install directory: $install_dir"
rm -rf "$install_dir"
fi
}
# Configure project
configure_project() {
local preset_name="$1"
local config_file="$2"
local exception_mode="$3"
log INFO "Configuring project: $preset_name"
local cmake_args=(cmake)
# Add configuration file if it exists
if [[ -f "$config_file" ]]; then
log DEBUG "Using configuration file: $config_file"
cmake_args+=(-C "$config_file")
else
log WARN "Configuration file not found: $config_file"
fi
# Add exception safety mode
if [[ "$exception_mode" == "conditional" ]]; then
cmake_args+=(-DENABLE_PLATFORM_CONDITIONAL_EXCEPTION=1)
fi
# Add preset
cmake_args+=(--preset "$preset_name")
# Execute configuration
run_command --until="-- Detecting CXX compile features - done" \
"${cmake_args[@]}"
}
# Build project
build_project() {
local preset_name="$1"
local num_jobs="$2"
local build_dir="$BUILD_SCRIPT_DIR/build/$preset_name"
log DEBUG "Building project: $preset_name (jobs: $num_jobs)"
# Monitor system resources during build
if command -v free &>/dev/null; then
local mem_before
mem_before=$(free -m | awk '/^Mem:/ {print $3}')
log DEBUG "Memory usage before build: ${mem_before}MB"
fi
local build_start
build_start=$(date +%s)
run_command cmake --build "$build_dir" -- -j"$num_jobs"
local build_end
build_end=$(date +%s)
local build_duration=$((build_end - build_start))
log INFO "Build completed in $(format_duration "$build_duration")"
if command -v free &>/dev/null; then
local mem_after
mem_after=$(free -m | awk '/^Mem:/ {print $3}')
log DEBUG "Memory usage after build: ${mem_after}MB"
fi
}
# Install project
install_project() {
local preset_name="$1"
local build_dir="$BUILD_SCRIPT_DIR/build/$preset_name"
local install_dir="$BUILD_SCRIPT_DIR/install/$preset_name"
log INFO "Installing project: $preset_name"
log DEBUG "Install directory: $install_dir"
create_directory "$install_dir"
run_command cmake --install "$build_dir" --prefix "$install_dir"
}
# Execute single build configuration
execute_build() {
local target="$1"
local build_type="$2"
local clean="$3"
local num_jobs="$4"
local exception_mode="$5"
log INFO "=========================================="
log INFO "Building: $target ($build_type)"
log INFO "=========================================="
# Setup environment if needed
if ! setup_qnx_environment "$target"; then
log ERROR "Failed to setup environment for: $target"
return "$EXIT_GENERAL_ERROR"
fi
# Export BUILD_TARGET for CMakePresets
export BUILD_TARGET="$target"
# Get configuration names
local preset_name
preset_name=$(get_preset_name "$target" "$build_type")
local config_file
config_file=$(get_config_file "$preset_name")
# Clean if requested
if [[ "$clean" == "true" ]]; then
clean_build "$preset_name"
fi
# Execute build steps
if ! configure_project "$preset_name" "$config_file" "$exception_mode"; then
log ERROR "Configuration failed for: $preset_name"
return "$EXIT_GENERAL_ERROR"
fi
if ! build_project "$preset_name" "$num_jobs"; then
log ERROR "Build failed for: $preset_name"
return "$EXIT_GENERAL_ERROR"
fi
if ! install_project "$preset_name"; then
log ERROR "Installation failed for: $preset_name"
return "$EXIT_GENERAL_ERROR"
fi
log INFO "Successfully built: $target ($build_type)"
return 0
}
# Execute batch builds
execute_batch_builds() {
local targets=("$@")
local num_jobs
num_jobs=$(get_cpu_count)
# Override with user setting if provided
if [[ -n "$NUM_JOBS" ]]; then
num_jobs="$NUM_JOBS"
fi
local total_builds=$((${#targets[@]} * ${#BUILD_TYPES[@]}))
local current_build=0
local failed_builds=()
log INFO "Starting batch build: ${#targets[@]} targets, ${#BUILD_TYPES[@]} configurations"
log INFO "Total builds to execute: $total_builds"
for target in "${targets[@]}"; do
for build_type in "${BUILD_TYPES[@]}"; do
current_build=$((current_build + 1))
log INFO ""
log INFO "Build $current_build of $total_builds"
if execute_build "$target" "$build_type" "$CLEAN_BUILD" "$num_jobs" "$EXCEPTION_SAFETY_MODE"; then
log INFO "✓ Build successful: $target ($build_type)"
else
log ERROR "✗ Build failed: $target ($build_type)"
failed_builds+=("$target:$build_type")
fi
done
done
# Summary
log INFO ""
log INFO "=========================================="
log INFO "Batch Build Summary"
log INFO "=========================================="
log INFO "Total builds: $total_builds"
log INFO "Successful: $((total_builds - ${#failed_builds[@]}))"
log INFO "Failed: ${#failed_builds[@]}"
if [[ ${#failed_builds[@]} -gt 0 ]]; then
log ERROR "Failed builds:"
for build in "${failed_builds[@]}"; do
log ERROR " - $build"
done
return "$EXIT_GENERAL_ERROR"
fi
return 0
}
# ------------------------------------------------------------------------------
# 12) Usage and Help
# ------------------------------------------------------------------------------
usage() {
cat <<EOF
OpenAA Build Script v$SCRIPT_VERSION
USAGE:
$SCRIPT_NAME [OPTIONS]
OPTIONS:
-h, --help Show this help message and exit
-c, --clean Clean build directories before building
-t, --build-type TYPE Build type: Debug or Release (default: Release)
-j, --jobs N Number of parallel jobs (default: auto-detect)
-b, --build-target TARGET Specific build target (see TARGETS below)
-e, --exception-safety MODE Exception safety: 'safe' or 'conditional' (default: conditional)
--qnx710-sdp PATH Path to QNX 7.10 SDP environment script
--qnx800-sdp PATH Path to QNX 8.0 SDP environment script
--all-targets Build all supported targets
--all-configs Build all configurations (Debug and Release)
-v, --verbose Enable verbose output
--dry-run Show what would be executed without doing it
--log-level LEVEL Set log level: TRACE, DEBUG, INFO, WARN, ERROR (default: INFO)
--log-file FILE Write logs to file
--log-json Use JSON format for log file
SUPPORTED TARGETS:
EOF
for target in "${SUPPORTED_TARGETS[@]}"; do
echo " - $target"
done
cat <<EOF
EXAMPLES:
# Build specific target with Release configuration
$SCRIPT_NAME -b gcc11_linux_x86_64 -t Release
# Build QNX target with clean build
$SCRIPT_NAME -c -b qcc12_qnx800_aarch64 --qnx800-sdp /path/to/qnx800/qnxsdp-env.sh
# Build all targets with all configurations
$SCRIPT_NAME --all-targets --all-configs --qnx710-sdp /path/to/qnx710 --qnx800-sdp /path/to/qnx800
# Debug mode with verbose logging
$SCRIPT_NAME -b gcc13_linux_x86_64 -v --log-level DEBUG --log-file build.log
ENVIRONMENT VARIABLES:
NO_COLOR Disable colored output
BUILD_TARGET Override build target (for CMakePresets.json)
EXIT CODES:
0 Success
1 General error
2 Misuse of shell command
126 Command cannot execute
127 Command not found
128 Invalid argument
130 Script terminated by Ctrl+C
143 Script terminated by SIGTERM
EOF
}
# ------------------------------------------------------------------------------
# 13) Argument Parsing
# ------------------------------------------------------------------------------
parse_arguments() {
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help)
usage
exit "$EXIT_SUCCESS"
;;
-c|--clean)
CLEAN_BUILD=true
;;
-t|--build-type)
shift
BUILD_TYPE="$1"
if [[ "$BUILD_TYPE" != "Debug" ]] && [[ "$BUILD_TYPE" != "Release" ]]; then
log FATAL "Invalid build type: $BUILD_TYPE (must be Debug or Release)"
fi
;;
-j|--jobs)
shift
NUM_JOBS="$1"
validate_number "$NUM_JOBS" 1 999 "job count" || exit $?
;;
-b|--build-target)
shift
BUILD_TARGET="$1"
validate_build_target "$BUILD_TARGET" || exit $?
;;
-e|--exception-safety)
shift
EXCEPTION_SAFETY_MODE="$1"
if [[ "$EXCEPTION_SAFETY_MODE" != "safe" ]] && [[ "$EXCEPTION_SAFETY_MODE" != "conditional" ]]; then
log FATAL "Invalid exception safety mode: $EXCEPTION_SAFETY_MODE (must be 'safe' or 'conditional')"
fi
;;
--qnx710-sdp)
shift
QNX710_SDP_PATH="$1"
validate_safe_string "$QNX710_SDP_PATH" '^[a-zA-Z0-9._/\-~ ]+$' "QNX 7.10 SDP path" || exit $?
;;
--qnx800-sdp)
shift
QNX800_SDP_PATH="$1"
validate_safe_string "$QNX800_SDP_PATH" '^[a-zA-Z0-9._/\-~ ]+$' "QNX 8.0 SDP path" || exit $?
;;
--all-targets)
ALL_TARGETS=true
;;
--all-configs)
ALL_CONFIGS=true
;;
-v|--verbose)
VERBOSE=true
;;
--dry-run)
DRY_RUN=true
;;
--log-level)
shift
LOG_LEVEL="$1"
if [[ ! ${LOG_LEVELS[$LOG_LEVEL]+isset} ]]; then
log FATAL "Invalid log level: $LOG_LEVEL"
fi
;;
--log-file)
shift
LOG_FILE="$1"
validate_safe_string "$LOG_FILE" '^[a-zA-Z0-9._/\-]+$' "log file path" || exit $?
;;
--log-json)
LOG_JSON=true
;;
-*)
log FATAL "Unknown option: $1"
;;
*)
log FATAL "Unexpected argument: $1"
;;
esac
shift
done
}
# ------------------------------------------------------------------------------
# 14) Main Function
# ------------------------------------------------------------------------------
main() {
# Initialize
BUILD_START_TIME=$(date +%s)
# Parse arguments
parse_arguments "$@"
# Initialize logging system
init_logging "$@"
# Log startup information
log INFO "OpenAA Build Script v$SCRIPT_VERSION"
log INFO "Host: $(hostname)"
log INFO "OS: $(detect_os)"
log INFO "CPU cores: $(get_cpu_count)"
log DEBUG "Script directory: $BUILD_SCRIPT_DIR"
# Setup signal handlers
setup_signals
# Check dependencies
check_dependencies
# Determine build targets
local targets=()
if [[ "$ALL_TARGETS" == "true" ]]; then
targets=("${SUPPORTED_TARGETS[@]}")
else
targets=("$BUILD_TARGET")
fi
# Determine build types
local build_types=()
if [[ "$ALL_CONFIGS" == "true" ]]; then
build_types=("${BUILD_TYPES[@]}")
else
build_types=("$BUILD_TYPE")
fi
# Execute builds
if [[ "$ALL_TARGETS" == "true" ]] || [[ "$ALL_CONFIGS" == "true" ]]; then
# Batch build mode
execute_batch_builds "${targets[@]}"
else
# Single build mode
local num_jobs
num_jobs="${NUM_JOBS:-$(get_cpu_count)}"
execute_build "$BUILD_TARGET" "$BUILD_TYPE" "$CLEAN_BUILD" "$num_jobs" "$EXCEPTION_SAFETY_MODE"
fi
# Record completion time
BUILD_END_TIME=$(date +%s)
# Exit with success
exit "$EXIT_SUCCESS"
}
# ------------------------------------------------------------------------------
# 15) Script Entry Point
# ------------------------------------------------------------------------------
# Ensure we're not being sourced
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi