Repository navigation
Expand file tree
/
Copy pathbenchmark.py
More file actions
2047 lines (1748 loc) · 75.6 KB
/
Copy pathbenchmark.py
File metadata and controls
2047 lines (1748 loc) · 75.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 python3
"""
Benchmark script for comparing EmbeddedProto vs NanoPB vs ArduinoJson on STM32 Nucleo-F446RE.
This script handles CLI argument parsing and validation for benchmarking scenarios.
It serves as the foundation for the automated size comparison tool.
"""
import argparse
import sys
import os
import subprocess
import shutil
import time
import sqlite3
import logging
from pathlib import Path
from typing import List, Dict, Optional, Tuple
from dataclasses import dataclass
from datetime import datetime, UTC
import glob
# Try to import tabulate for pretty table formatting, fall back to manual formatting
try:
from tabulate import tabulate
TABULATE_AVAILABLE = True
except ImportError:
TABULATE_AVAILABLE = False
print("Note: 'tabulate' library not found. Using manual table formatting. "
"Install with 'pip install tabulate' for better output.")
# Valid library choices
VALID_LIBRARIES = ['ArduinoJson', 'EmbeddedProto', 'NanoPB', 'FlatBuffers', 'Zcbor', 'Baseline']
# Library name mapping for External directory
LIBRARY_TO_EXTERNAL_DIR = {
'NanoPB': 'Nanopb',
'FlatBuffers': 'flatcc',
'Zcbor': 'zcbor',
'EmbeddedProto': 'EmbeddedProto',
'ArduinoJson': 'ArduinoJson',
'Baseline': None # Baseline has no external library
}
@dataclass
class StaticSizes:
"""Data class to hold static size metrics (text, data, bss from arm-none-eabi-size)."""
text_bytes: int
data_bytes: int
bss_bytes: int
@dataclass
class DynamicMetrics:
"""Data class to hold dynamic metrics from device."""
cpu_cycles: Optional[int]
n_bytes_in_buffer: Optional[int]
message_size_bytes: Optional[int]
peak_ram_bytes: Optional[int]
@dataclass
class GitInfo:
"""Data class to hold git repository information."""
commit_hash: str
branch: Optional[str]
tag: Optional[str]
is_modified: bool
def parse_cmake_optimization_flags(cmake_path: str = 'CMakeLists.txt') -> Dict[str, str]:
"""
Parse optimization flags from CMakeLists.txt for each build type.
Args:
cmake_path: Path to the CMakeLists.txt file (default: 'CMakeLists.txt')
Returns:
Dictionary mapping build type (e.g., 'Release', 'Debug') to optimization flags string
Raises:
FileNotFoundError: If CMakeLists.txt doesn't exist
ValueError: If no optimization flags could be parsed
"""
import re
cmake_file = Path(cmake_path)
if not cmake_file.exists():
raise FileNotFoundError(f"CMakeLists.txt not found at: {cmake_path}")
try:
content = cmake_file.read_text()
except Exception as e:
raise ValueError(f"Failed to read CMakeLists.txt: {str(e)}") from e
flags = {}
# Pattern to match: set(CMAKE_CXX_FLAGS_<TYPE> "flags" ...)
# Example: set(CMAKE_CXX_FLAGS_RELEASE "-Os -DNDEBUG -ffunction-sections -fdata-sections" CACHE STRING "" FORCE)
pattern = r'set\s*\(\s*CMAKE_CXX_FLAGS_(\w+)\s+"([^"]+)"'
matches = re.findall(pattern, content)
# Expand ${VAR} references to plain set(VAR "value") definitions in the same file,
# so the stored flags show what the compiler actually received.
variables = dict(re.findall(r'set\s*\(\s*(\w+)\s+"([^"$]*)"\s*\)', content))
for build_type, flag_string in matches:
for name, value in variables.items():
flag_string = flag_string.replace('${' + name + '}', value)
# Capitalize first letter, lowercase rest (e.g., RELEASE -> Release)
build_type_normalized = build_type.capitalize()
flags[build_type_normalized] = flag_string
if not flags:
raise ValueError(f"No CMAKE_CXX_FLAGS_* definitions found in {cmake_path}")
return flags
def get_optimization_flags(build_type: str) -> str:
"""
Get optimization flags for a specific build type by parsing CMakeLists.txt.
Args:
build_type: Build type ('Release' or 'Debug')
Returns:
Optimization flags string for the specified build type
Raises:
ValueError: If build type is not found in CMakeLists.txt
"""
try:
flags = parse_cmake_optimization_flags()
if build_type not in flags:
raise ValueError(f"Build type '{build_type}' not found in CMakeLists.txt. "
f"Available types: {', '.join(flags.keys())}")
return flags[build_type]
except FileNotFoundError:
# Fallback to hardcoded defaults if CMakeLists.txt is not found
fallback_flags = {
'Release': '-Os -DNDEBUG -ffunction-sections -fdata-sections',
'Debug': '-Og -g -DDEBUG'
}
return fallback_flags.get(build_type, '')
def get_valid_build_types() -> List[str]:
"""
Get list of valid build types from CMakeLists.txt.
Returns:
List of valid build type names (e.g., ['Release', 'Debug'])
"""
try:
flags = parse_cmake_optimization_flags()
return list(flags.keys())
except (FileNotFoundError, ValueError):
# Fallback to defaults
return ['Release', 'Debug']
@dataclass
class BenchmarkResult:
"""Data class to hold complete benchmark results for database storage."""
library: str
scenario: str
text_bytes: int
data_bytes: int
bss_bytes: int
cpu_cycles: Optional[int]
n_bytes_in_buffer: Optional[int]
message_size_bytes: Optional[int]
peak_ram_bytes: Optional[int]
library_commit_hash: str
library_branch: Optional[str]
library_tag: Optional[str]
library_modified: bool
timestamp: str
build_type: str
optimization_flags: str
benchmark_mode: str
def get_available_libraries() -> List[str]:
"""
Get list of available libraries.
Returns:
List of available library names: ['ArduinoJson', 'EmbeddedProto', 'NanoPB', 'Baseline']
"""
return VALID_LIBRARIES
def get_scenarios_for_library(library: str) -> List[str]:
"""
Get list of available scenarios for a specific library.
Args:
library: Library name
Returns:
List of scenario names (without .cpp extension)
Raises:
FileNotFoundError: If Scenarios directory doesn't exist
ValueError: If library is not valid or has no scenarios
"""
scenarios_dir = Path('Scenarios')
if not scenarios_dir.exists():
raise FileNotFoundError("Scenarios directory not found. Expected to find 'Scenarios/' directory.")
if library not in VALID_LIBRARIES:
raise ValueError(f"Invalid library '{library}'. Valid libraries are: {', '.join(VALID_LIBRARIES)}")
library_dir = scenarios_dir / library
if not library_dir.exists() or not library_dir.is_dir():
raise ValueError(f"No scenarios found for library '{library}'. Directory does not exist.")
# Find all .cpp files, excluding helper files
cpp_files = [
f.stem for f in library_dir.glob('*.cpp')
if not f.stem.startswith('helper_')
]
if not cpp_files:
raise ValueError(f"No valid scenarios found for library '{library}'. No .cpp files found (excluding helper_*).")
return cpp_files
def validate_library_scenario_combination(library: str, scenario: str) -> bool:
"""
Validate that a library/scenario combination is valid.
Args:
library: Library name
scenario: Scenario name
Returns:
True if combination is valid, False otherwise
"""
try:
scenarios = get_scenarios_for_library(library)
return scenario in scenarios
except (FileNotFoundError, ValueError):
return False
def get_all_scenario_combinations() -> List[Tuple[str, str]]:
"""
Get all valid library/scenario combinations.
Returns:
List of (library, scenario) tuples
"""
combinations = []
for library in VALID_LIBRARIES:
try:
scenarios = get_scenarios_for_library(library)
for scenario in scenarios:
combinations.append((library, scenario))
except (FileNotFoundError, ValueError):
# Skip libraries with no valid scenarios
continue
return combinations
def discover_scenarios() -> Dict[str, List[str]]:
"""
Discover available scenarios from the Scenarios directory structure.
Returns:
Dictionary mapping library names to lists of available scenario names.
Note: This function is maintained for backward compatibility.
"""
scenarios = {}
for library in VALID_LIBRARIES:
try:
scenarios[library] = get_scenarios_for_library(library)
except (FileNotFoundError, ValueError):
# Skip libraries with no valid scenarios
continue
return scenarios
def get_library_git_info(library: str) -> Optional[GitInfo]:
"""
Extract git information from library repositories in External/ directory.
Args:
library: Library name (e.g., 'EmbeddedProto', 'NanoPB', 'ArduinoJson', 'Baseline')
Returns:
GitInfo dataclass with commit_hash, branch, tag, and is_modified status
Returns None if library has no external repository (e.g., Baseline)
Raises:
FileNotFoundError: If library directory doesn't exist
ValueError: If library is not valid
"""
# Validate library
if library not in VALID_LIBRARIES:
raise ValueError(f"Invalid library '{library}'. Valid libraries are: {', '.join(VALID_LIBRARIES)}")
# Get external directory path (handle library name mapping)
external_dir_name = LIBRARY_TO_EXTERNAL_DIR.get(library)
if external_dir_name is None:
# Baseline has no external library
return None
external_path = Path('External') / external_dir_name
# Check if external directory exists
if not external_path.exists():
raise FileNotFoundError(f"External directory not found for library '{library}': {external_path}")
# Check if it's a git repository
git_dir = external_path / '.git'
if not git_dir.exists():
raise ValueError(f"Directory is not a git repository: {external_path}")
try:
# Get current commit hash
commit_hash_result = subprocess.run(
['git', 'rev-parse', 'HEAD'],
cwd=external_path,
capture_output=True,
text=True,
check=True
)
commit_hash = commit_hash_result.stdout.strip()
# Get current branch (handles detached HEAD)
branch = None
try:
branch_result = subprocess.run(
['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
cwd=external_path,
capture_output=True,
text=True,
check=True
)
branch = branch_result.stdout.strip()
# Handle detached HEAD case
if branch == 'HEAD':
branch = None
except subprocess.CalledProcessError:
# If we can't get branch, that's okay - it might be detached HEAD
branch = None
# Get tag at HEAD (if exact match exists)
tag = None
try:
tag_result = subprocess.run(
['git', 'describe', '--tags', '--exact-match'],
cwd=external_path,
capture_output=True,
text=True,
check=True
)
tag = tag_result.stdout.strip()
except subprocess.CalledProcessError:
# No exact tag match - that's okay
tag = None
# Check for uncommitted modifications
status_result = subprocess.run(
['git', 'status', '--porcelain'],
cwd=external_path,
capture_output=True,
text=True,
check=True
)
is_modified = bool(status_result.stdout.strip())
return GitInfo(
commit_hash=commit_hash,
branch=branch,
tag=tag,
is_modified=is_modified
)
except subprocess.CalledProcessError as e:
error_msg = f"Failed to extract git information from {external_path}: {str(e)}"
if e.stderr:
error_msg += f"\nGit error: {e.stderr.strip()}"
raise ValueError(error_msg) from e
except Exception as e:
raise ValueError(f"Unexpected error extracting git information: {str(e)}") from e
def print_error(message: str, exit_code: int = 1) -> None:
"""
Print error message to stderr and exit with specified code.
Args:
message: Error message to display
exit_code: Exit code to use
"""
print(f"ERROR: {message}", file=sys.stderr)
sys.exit(exit_code)
def list_scenario_combinations() -> None:
"""
List all available library/scenario combinations.
"""
combinations = get_all_scenario_combinations()
if not combinations:
print("No valid library/scenario combinations found.")
return
print("Available library/scenario combinations:")
for library, scenario in combinations:
print(f" {library}/{scenario}")
print(f"\nTotal combinations: {len(combinations)}")
def get_user_confirmation(prompt: str) -> bool:
"""
Get user confirmation with yes/no prompt.
Args:
prompt: The prompt message to display
Returns:
True if user confirms (yes/y), False otherwise
"""
while True:
response = input(f"{prompt} (yes/no): ").strip().lower()
if response in ['yes', 'y']:
return True
elif response in ['no', 'n']:
return False
else:
print("Please enter 'yes' or 'no'.")
def clean_build_artifacts() -> None:
"""
Remove all build results and generated files.
This function cleans:
- All subdirectories in build/
- Generated .h, .c, .pb.h, .pb.c files in Generated/
- Does NOT remove Generated/CMakeLists.txt
"""
print("Cleaning build artifacts...")
# Clean build directory
build_dir = Path('build')
if build_dir.exists():
# Remove all library subdirectories in build/
for item in build_dir.iterdir():
if item.is_dir():
print(f" Removing {item}")
shutil.rmtree(item)
else:
# Also remove any files in the build root
print(f" Removing {item}")
item.unlink()
print(f"Cleaned build directory: {build_dir}")
else:
print("Build directory does not exist, nothing to clean.")
# Clean generated files in Generated/ directory
generated_dir = Path('Generated')
if generated_dir.exists():
# Patterns for generated files to remove
patterns = ['*.h', '*.c', '*.pb.h', '*.pb.c']
files_to_preserve = ['CMakeLists.txt']
for pattern in patterns:
for file_path in generated_dir.glob(pattern):
if file_path.name not in files_to_preserve:
print(f" Removing {file_path}")
file_path.unlink()
print(f"Cleaned generated files in: {generated_dir}")
else:
print("Generated directory does not exist, nothing to clean.")
print("Clean completed.")
def build_firmware(
library: str,
scenario: str,
build_type: str = 'Release',
benchmark_mode: str = 'normal'
) -> str:
"""
Build firmware for a specific library/scenario combination using CMake.
Each library/scenario combination gets its own build directory to allow
comparing build results without overwriting previous builds.
Args:
library: Library name (e.g., 'EmbeddedProto')
scenario: Scenario name (e.g., 'simple_types_serialize_max')
build_type: CMake build type ('Release' or 'Debug'), defaults to 'Release'
benchmark_mode: Benchmark mode ('normal' or 'partial'), defaults to 'normal'
Returns:
Path to the built ELF file: 'build/{library}/{scenario}/bin/nucleo_f446re_app.elf'
Raises:
ValueError: If library/scenario combination is invalid
FileNotFoundError: If required tools are not found
subprocess.CalledProcessError: If build process fails
"""
# Validate the library/scenario combination
if not validate_library_scenario_combination(library, scenario):
raise ValueError(f"Invalid library/scenario combination: {library}/{scenario}")
# Validate build type
valid_types = get_valid_build_types()
if build_type not in valid_types:
raise ValueError(f"Invalid build type '{build_type}'. Valid types are: {', '.join(valid_types)}")
# Check if arm-none-eabi-gcc is available
if not shutil.which('arm-none-eabi-gcc'):
raise FileNotFoundError(
"arm-none-eabi-gcc not found. Please install the ARM toolchain. "
"On Ubuntu/Debian: sudo apt install gcc-arm-none-eabi"
)
# Check if cmake is available
if not shutil.which('cmake'):
raise FileNotFoundError(
"cmake not found. Please install CMake. "
"On Ubuntu/Debian: sudo apt install cmake"
)
# Validate benchmark mode
if benchmark_mode not in ['normal', 'partial']:
raise ValueError(f"Invalid benchmark mode '{benchmark_mode}'. Valid modes are: normal, partial")
# Use library/mode/scenario-specific build directory
# This prevents CMake cache contamination between benchmark modes.
build_dir = Path('build') / library / benchmark_mode / scenario
elf_path = build_dir / 'bin' / 'nucleo_f446re_app.elf'
# Create build directory if it doesn't exist (no need to clean - CMake handles incremental builds)
if not build_dir.exists():
print(f"Creating build directory: {build_dir}")
build_dir.mkdir(parents=True)
print(f"Building {library}/{scenario} ({build_type}, mode={benchmark_mode})...")
print(f"Build directory: {build_dir}")
print(f"Optimization flags: {get_optimization_flags(build_type)}")
try:
# Run cmake configuration with build type
print("Running cmake configuration...")
cmake_config_result = subprocess.run(
['cmake', '-B', str(build_dir),
f'-DLIBRARY={library}',
f'-DSCENARIO={scenario}',
f'-DBENCHMARK_MODE={benchmark_mode}',
f'-DCMAKE_BUILD_TYPE={build_type}'],
capture_output=True,
text=True,
check=True
)
print("CMake configuration completed successfully.")
# Run cmake build
print("Running cmake build...")
cmake_build_result = subprocess.run(
['cmake', '--build', str(build_dir)],
capture_output=True,
text=True,
check=True
)
print("CMake build completed successfully.")
# Verify ELF file exists
if not elf_path.exists():
raise FileNotFoundError(f"Expected ELF file not found: {elf_path}")
print(f"Build successful. ELF file: {elf_path}")
return str(elf_path)
except subprocess.CalledProcessError as e:
# Display build error information
error_output = e.stderr or e.stdout or "Unknown build error"
print(f"Build failed with return code {e.returncode}:", file=sys.stderr)
print(error_output, file=sys.stderr)
# Check for common error patterns
if "arm-none-eabi-gcc" in error_output and "not found" in error_output:
raise FileNotFoundError(
"arm-none-eabi-gcc not found. Please install the ARM toolchain. "
"On Ubuntu/Debian: sudo apt install gcc-arm-none-eabi"
) from e
elif "cmake" in error_output and "not found" in error_output:
raise FileNotFoundError(
"cmake not found. Please install CMake. "
"On Ubuntu/Debian: sudo apt install cmake"
) from e
else:
# Re-raise with additional context
raise subprocess.CalledProcessError(
e.returncode,
e.cmd,
output=error_output
) from e
def extract_static_sizes(elf_path: str) -> StaticSizes:
"""
Extract static size metrics from ELF file using arm-none-eabi-size.
Args:
elf_path: Path to the ELF file
Returns:
StaticSizes dataclass with flash_usage_bytes and static_ram_usage_bytes
Raises:
FileNotFoundError: If ELF file doesn't exist
FileNotFoundError: If arm-none-eabi-size is not installed
subprocess.CalledProcessError: If arm-none-eabi-size fails to run
"""
# Validate ELF file exists
elf_file = Path(elf_path)
if not elf_file.exists():
raise FileNotFoundError(f"ELF file not found: {elf_path}")
# Check if arm-none-eabi-size is available
if not shutil.which('arm-none-eabi-size'):
raise FileNotFoundError(
"arm-none-eabi-size not found. Please install the ARM toolchain. "
"On Ubuntu/Debian: sudo apt install binutils-arm-none-eabi"
)
# Check if arm-none-eabi-nm is available for more accurate RAM calculation
nm_available = shutil.which('arm-none-eabi-nm') is not None
try:
# Run arm-none-eabi-size (default format gives text, data, bss summary)
result = subprocess.run(
['arm-none-eabi-size', elf_path],
capture_output=True,
text=True,
check=True
)
# Parse output - expected format: "text data bss dec hex filename"
lines = result.stdout.strip().split('\n')
if len(lines) < 1:
raise ValueError(f"Unexpected output format from arm-none-eabi-size: {result.stdout}")
# Find the first line that contains numeric data (skip header line)
numeric_line = None
for line in lines:
line = line.strip()
if line and line[0].isdigit():
numeric_line = line
break
if not numeric_line:
raise ValueError(f"Could not find numeric data in arm-none-eabi-size output: {result.stdout}")
# Parse the numeric line
parts = numeric_line.split()
if len(parts) < 4:
raise ValueError(f"Unexpected output format from arm-none-eabi-size: {result.stdout}")
# Extract text, data, bss values (they should be the first 3 numeric values)
try:
text_size = int(parts[0])
data_size = int(parts[1])
bss_size = int(parts[2])
except (ValueError, IndexError) as e:
raise ValueError(f"Could not parse size values from arm-none-eabi-size output: {result.stdout}") from e
# The linker script reserves the heap and stack in a ._user_heap_stack section which
# the berkeley format counts as bss. It is a constant, not memory the library uses.
sections = subprocess.run(
['arm-none-eabi-size', '-A', elf_path],
capture_output=True,
text=True,
check=True
)
for line in sections.stdout.split('\n'):
parts = line.split()
if len(parts) >= 2 and parts[0] == '._user_heap_stack':
bss_size -= int(parts[1])
return StaticSizes(
text_bytes=text_size,
data_bytes=data_size,
bss_bytes=bss_size
)
except subprocess.CalledProcessError as e:
error_output = e.stderr or e.stdout or "Unknown error from arm-none-eabi-size"
raise subprocess.CalledProcessError(
e.returncode,
e.cmd,
output=f"arm-none-eabi-size failed: {error_output}"
) from e
def _calculate_static_ram_with_nm(elf_path: str, data_size: int) -> int:
"""
Calculate static RAM usage using arm-none-eabi-nm.
Args:
elf_path: Path to the ELF file
data_size: Data size from arm-none-eabi-size (used as fallback)
Returns:
Static RAM usage in bytes
Raises:
subprocess.CalledProcessError: If arm-none-eabi-nm fails to run
"""
try:
# Run arm-none-eabi-nm to get symbol addresses
result = subprocess.run(
['arm-none-eabi-nm', '--defined-only', '--format=sysv', '--radix=d', elf_path],
capture_output=True,
text=True,
check=True
)
# Parse symbol addresses
ebss_addr = None
sdata_addr = None
for line in result.stdout.split('\n'):
line = line.strip()
if not line:
continue
# Parse nm output - it can be either space-separated or pipe-separated
if '|' in line:
# Pipe-separated format: symbol|address|type|size|section
parts = line.split('|')
if len(parts) >= 2:
symbol_name = parts[0].strip()
try:
address = int(parts[1].strip())
if symbol_name == '_ebss':
ebss_addr = address
elif symbol_name == '_sdata':
sdata_addr = address
except ValueError:
continue
else:
# Space-separated format: address type size section symbol
parts = line.split()
if len(parts) >= 4:
symbol_name = parts[-1]
if symbol_name == '_ebss':
ebss_addr = int(parts[0])
elif symbol_name == '_sdata':
sdata_addr = int(parts[0])
# Calculate static RAM usage
if ebss_addr is not None and sdata_addr is not None and ebss_addr > sdata_addr:
# Static RAM usage is the difference between _ebss and _sdata
return ebss_addr - sdata_addr
else:
# Fallback to data_size if we can't get proper symbols
return data_size
except subprocess.CalledProcessError as e:
# If nm fails, fallback to data_size
return data_size
except subprocess.CalledProcessError as e:
# Display build error information
error_output = e.stderr or e.stdout or "Unknown build error"
print(f"Build failed with return code {e.returncode}:", file=sys.stderr)
print(error_output, file=sys.stderr)
# Check for common error patterns
if "arm-none-eabi-gcc" in error_output and "not found" in error_output:
raise FileNotFoundError(
"arm-none-eabi-gcc not found. Please install the ARM toolchain. "
"On Ubuntu/Debian: sudo apt install gcc-arm-none-eabi"
) from e
elif "cmake" in error_output and "not found" in error_output:
raise FileNotFoundError(
"cmake not found. Please install CMake. "
"On Ubuntu/Debian: sudo apt install cmake"
) from e
else:
# Re-raise with additional context
raise subprocess.CalledProcessError(
e.returncode,
e.cmd,
output=error_output
) from e
def flash_device(elf_path: str) -> bool:
"""
Flash the device using OpenOCD.
Args:
elf_path: Path to the ELF file to flash
Returns:
True if flashing succeeded, False if failed
Raises:
FileNotFoundError: If OpenOCD is not installed
"""
# Check if OpenOCD is installed
if not shutil.which('openocd'):
raise FileNotFoundError(
"openocd not found. Please install OpenOCD. "
"On Ubuntu/Debian: sudo apt install openocd"
)
# Check if ELF file exists
elf_file = Path(elf_path)
if not elf_file.exists():
raise FileNotFoundError(f"ELF file not found: {elf_path}")
print(f"Flashing device with {elf_path}...")
# OpenOCD command with retry logic (up to 3 attempts)
openocd_cmd = [
'openocd',
'-f', 'interface/stlink.cfg',
'-f', 'target/stm32f4x.cfg',
'-c', f'program {elf_path} verify reset exit'
]
max_attempts = 3
attempt = 1
while attempt <= max_attempts:
print(f"Flashing attempt {attempt}/{max_attempts}...")
try:
# Run OpenOCD command
result = subprocess.run(
openocd_cmd,
capture_output=True,
text=True,
check=True
)
print("Device flashing completed successfully.")
return True
except subprocess.CalledProcessError as e:
error_output = e.stderr or e.stdout or "Unknown flashing error"
# Check for ST-Link connection errors
if any(pattern in error_output.lower() for pattern in
['error:', 'failed', 'no device found', 'st-link', 'connection failed']):
if attempt < max_attempts:
print(f"ST-Link connection issue detected. Retrying in 2 seconds... (Attempt {attempt}/{max_attempts})")
print(f"Error details: {error_output.strip()}")
time.sleep(2)
attempt += 1
continue
else:
print(f"ST-Link connection failed after {max_attempts} attempts.")
print(f"Error: {error_output.strip()}")
print("Please ensure your STM32 Nucleo-F446RE board is connected via ST-Link.")
return False
else:
print(f"Flashing failed: {error_output.strip()}")
return False
except Exception as e:
print(f"Unexpected error during flashing: {str(e)}")
return False
return False
# The globals the firmware fills for the tool, see Firmware/Nucleo-F446RE/Core/Src/main.cpp,
# each mapped to the field of DynamicMetrics it lands in. Only the cycle counter is required.
DEVICE_SYMBOLS = {
'g_cpu_cycles_used': 'cpu_cycles',
'g_n_bytes_in_buffer': 'n_bytes_in_buffer',
'g_message_size_bytes': 'message_size_bytes',
'g_peak_ram_bytes': 'peak_ram_bytes',
}
def no_dynamic_metrics() -> DynamicMetrics:
"""The metrics of a build that was not run on the device."""
return DynamicMetrics(cpu_cycles=None, n_bytes_in_buffer=None, message_size_bytes=None, peak_ram_bytes=None)
def find_device_symbols(elf_path: str) -> Dict[str, int]:
"""
Look up the addresses of the DEVICE_SYMBOLS in the ELF file with arm-none-eabi-nm.
Returns:
Dictionary of symbol name to address, only for the symbols the firmware defines.
"""
nm_result = subprocess.run(
['arm-none-eabi-nm', '--defined-only', '--format=sysv', '--radix=d', elf_path],
capture_output=True,
text=True,
check=True
)
addresses: Dict[str, int] = {}
for line in nm_result.stdout.split('\n'):
line = line.strip()
if not line:
continue
# sysv output is pipe separated: symbol|address|type|size|section
if '|' in line:
parts = line.split('|')
symbol_name = parts[0].strip()
address_text = parts[1].strip() if len(parts) >= 2 else ''
else:
parts = line.split()
symbol_name = parts[-1] if len(parts) >= 4 else ''
address_text = parts[0] if len(parts) >= 4 else ''
if symbol_name in DEVICE_SYMBOLS:
try:
addresses[symbol_name] = int(address_text)
except ValueError:
continue
return addresses
def read_dynamic_metrics(elf_path: str, delay_seconds: float = 2) -> DynamicMetrics:
"""
Read the dynamic metrics from the running device via OpenOCD/SWD.
The firmware runs the scenario once and leaves the results in the globals of DEVICE_SYMBOLS.
After a delay the core is halted, every symbol is read with mdw, and the board is reset so
the LED stops blinking.
Args:
elf_path: Path to the ELF file
delay_seconds: Time to wait for the scenario to complete
Returns:
DynamicMetrics with None for every value that could not be read
Raises:
FileNotFoundError: If required tools (arm-none-eabi-nm, openocd) are not installed
"""
if not shutil.which('openocd'):
raise FileNotFoundError(
"openocd not found. Please install OpenOCD. "
"On Ubuntu/Debian: sudo apt install openocd"
)
if not shutil.which('arm-none-eabi-nm'):
raise FileNotFoundError(
"arm-none-eabi-nm not found. Please install the ARM toolchain. "
"On Ubuntu/Debian: sudo apt install binutils-arm-none-eabi"
)
if not Path(elf_path).exists():
print("Warning: ELF file not found for dynamic metrics reading")
return no_dynamic_metrics()
print(f"Reading dynamic metrics from device...")
try:
addresses = find_device_symbols(elf_path)
if 'g_cpu_cycles_used' not in addresses:
print("Warning: Could not find required symbols in ELF file")
return no_dynamic_metrics()
for symbol_name in DEVICE_SYMBOLS:
if symbol_name in addresses:
print(f" {symbol_name} at 0x{addresses[symbol_name]:08X}")
else:
print(f" {symbol_name} not found (not measured by this firmware)")
print(f"Waiting {delay_seconds} seconds for scenario to complete...")
time.sleep(delay_seconds)
openocd_cmd = [
'openocd',
'-f', 'interface/stlink.cfg',
'-f', 'target/stm32f4x.cfg',
'-c', 'init',
'-c', 'halt',
]
for address in addresses.values():
openocd_cmd.extend(['-c', f'mdw 0x{address:08x}'])
# Reset the peripherals so the LED stops blinking and keep the core halted: the board
# is done until the next flash.
openocd_cmd.extend([
'-c', 'reset halt',
'-c', 'exit'
])
try:
result = subprocess.run(openocd_cmd, capture_output=True, text=True, check=True)
except subprocess.CalledProcessError as e:
error_output = e.stderr or e.stdout or "Unknown OpenOCD error"
print(f"Warning: Could not read dynamic metrics: {error_output.strip()}")
return no_dynamic_metrics()
# OpenOCD prints "0xaddress: value" for every mdw, to stdout or stderr
all_output = result.stdout + "\n" + result.stderr
values: Dict[str, Optional[int]] = {field: None for field in DEVICE_SYMBOLS.values()}
for line in all_output.split('\n'):
line = line.strip().lower()
for symbol_name, address in addresses.items():
if f"0x{address:08x}" in line:
parts = line.split(':')
if len(parts) >= 2:
try:
values[DEVICE_SYMBOLS[symbol_name]] = int(parts[1].strip().split()[0], 16)
except (ValueError, IndexError):