forked from platformio/platform-espressif32
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathespidf.py
1849 lines (1536 loc) · 60.4 KB
/
espidf.py
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
# Copyright 2020-present PlatformIO <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Espressif IDF
Espressif IoT Development Framework for ESP32 MCU
https://github.com/espressif/esp-idf
"""
import copy
import json
import subprocess
import sys
import shutil
import os
import re
import platform as sys_platform
import click
import semantic_version
from SCons.Script import (
ARGUMENTS,
COMMAND_LINE_TARGETS,
DefaultEnvironment,
)
from platformio import fs, __version__
from platformio.compat import IS_WINDOWS
from platformio.proc import exec_command
from platformio.builder.tools.piolib import ProjectAsLibBuilder
from platformio.package.version import get_original_version, pepver_to_semver
# Added to avoid conflicts between installed Python packages from
# the IDF virtual environment and PlatformIO Core
# Note: This workaround can be safely deleted when PlatformIO 6.1.7 is released
if os.environ.get("PYTHONPATH"):
del os.environ["PYTHONPATH"]
env = DefaultEnvironment()
env.SConscript("_embed_files.py", exports="env")
# Allow changes in folders of managed components
os.environ["IDF_COMPONENT_OVERWRITE_MANAGED_COMPONENTS"] = "1"
platform = env.PioPlatform()
board = env.BoardConfig()
mcu = board.get("build.mcu", "esp32")
idf_variant = mcu.lower()
IDF5 = (
platform.get_package_version("framework-espidf")
.split(".")[1]
.startswith("5")
)
IDF_ENV_VERSION = "1.0.0"
FRAMEWORK_DIR = platform.get_package_dir("framework-espidf")
TOOLCHAIN_DIR = platform.get_package_dir(
"toolchain-%s" % ("riscv32-esp" if mcu in ("esp32c2", "esp32c3", "esp32c6", "esp32h2") else ("xtensa-%s" % mcu))
)
assert os.path.isdir(FRAMEWORK_DIR)
assert os.path.isdir(TOOLCHAIN_DIR)
# The latest IDF uses a standalone GDB package which requires at least PlatformIO 6.1.11
if (
["espidf"] == env.get("PIOFRAMEWORK")
and semantic_version.Version.coerce(__version__)
<= semantic_version.Version("6.1.10")
and "__debug" in COMMAND_LINE_TARGETS
):
print("Warning! Debugging an IDF project requires PlatformIO Core >= 6.1.11!")
# Arduino framework as a component is not compatible with ESP-IDF >5.2
if "arduino" in env.subst("$PIOFRAMEWORK"):
ARDUINO_FRAMEWORK_DIR = platform.get_package_dir("framework-arduinoespressif32")
# Possible package names in 'package@version' format is not compatible with CMake
if "@" in os.path.basename(ARDUINO_FRAMEWORK_DIR):
new_path = os.path.join(
os.path.dirname(ARDUINO_FRAMEWORK_DIR),
os.path.basename(ARDUINO_FRAMEWORK_DIR).replace("@", "-"),
)
os.rename(ARDUINO_FRAMEWORK_DIR, new_path)
ARDUINO_FRAMEWORK_DIR = new_path
assert ARDUINO_FRAMEWORK_DIR and os.path.isdir(ARDUINO_FRAMEWORK_DIR)
BUILD_DIR = env.subst("$BUILD_DIR")
PROJECT_DIR = env.subst("$PROJECT_DIR")
PROJECT_SRC_DIR = env.subst("$PROJECT_SRC_DIR")
CMAKE_API_REPLY_PATH = os.path.join(".cmake", "api", "v1", "reply")
SDKCONFIG_PATH = os.path.expandvars(board.get(
"build.esp-idf.sdkconfig_path",
os.path.join(PROJECT_DIR, "sdkconfig.%s" % env.subst("$PIOENV")),
))
def get_project_lib_includes(env):
project = ProjectAsLibBuilder(env, "$PROJECT_DIR")
project.install_dependencies()
project.search_deps_recursive()
paths = []
for lb in env.GetLibBuilders():
if not lb.dependent:
continue
lb.env.PrependUnique(CPPPATH=lb.get_include_dirs())
paths.extend(lb.env["CPPPATH"])
DefaultEnvironment().Replace(__PIO_LIB_BUILDERS=None)
return paths
def is_cmake_reconfigure_required(cmake_api_reply_dir):
cmake_cache_file = os.path.join(BUILD_DIR, "CMakeCache.txt")
cmake_txt_files = [
os.path.join(PROJECT_DIR, "CMakeLists.txt"),
os.path.join(PROJECT_SRC_DIR, "CMakeLists.txt"),
]
cmake_preconf_dir = os.path.join(BUILD_DIR, "config")
deafult_sdk_config = os.path.join(PROJECT_DIR, "sdkconfig.defaults")
for d in (cmake_api_reply_dir, cmake_preconf_dir):
if not os.path.isdir(d) or not os.listdir(d):
return True
if not os.path.isfile(cmake_cache_file):
return True
if not os.path.isfile(os.path.join(BUILD_DIR, "build.ninja")):
return True
if not os.path.isfile(SDKCONFIG_PATH) or os.path.getmtime(
SDKCONFIG_PATH
) > os.path.getmtime(cmake_cache_file):
return True
if os.path.isfile(deafult_sdk_config) and os.path.getmtime(
deafult_sdk_config
) > os.path.getmtime(cmake_cache_file):
return True
if any(
os.path.getmtime(f) > os.path.getmtime(cmake_cache_file)
for f in cmake_txt_files + [cmake_preconf_dir, FRAMEWORK_DIR]
):
return True
return False
def is_proper_idf_project():
return all(
os.path.isfile(path)
for path in (
os.path.join(PROJECT_DIR, "CMakeLists.txt"),
os.path.join(PROJECT_SRC_DIR, "CMakeLists.txt"),
)
)
def collect_src_files():
return [
f
for f in env.MatchSourceFiles("$PROJECT_SRC_DIR", env.get("SRC_FILTER"))
if not f.endswith((".h", ".hpp"))
]
def normalize_path(path):
if PROJECT_DIR in path:
path = path.replace(PROJECT_DIR, "${CMAKE_SOURCE_DIR}")
return fs.to_unix_path(path)
def create_default_project_files():
root_cmake_tpl = """cmake_minimum_required(VERSION 3.16.0)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(%s)
"""
prj_cmake_tpl = """# This file was automatically generated for projects
# without default 'CMakeLists.txt' file.
FILE(GLOB_RECURSE app_sources %s/*.*)
idf_component_register(SRCS ${app_sources})
"""
if not os.listdir(PROJECT_SRC_DIR):
# create a default main file to make CMake happy during first init
with open(os.path.join(PROJECT_SRC_DIR, "main.c"), "w") as fp:
fp.write("void app_main() {}")
project_dir = PROJECT_DIR
if not os.path.isfile(os.path.join(project_dir, "CMakeLists.txt")):
with open(os.path.join(project_dir, "CMakeLists.txt"), "w") as fp:
fp.write(root_cmake_tpl % os.path.basename(project_dir))
project_src_dir = PROJECT_SRC_DIR
if not os.path.isfile(os.path.join(project_src_dir, "CMakeLists.txt")):
with open(os.path.join(project_src_dir, "CMakeLists.txt"), "w") as fp:
fp.write(prj_cmake_tpl % normalize_path(PROJECT_SRC_DIR))
def get_cmake_code_model(src_dir, build_dir, extra_args=None):
cmake_api_dir = os.path.join(build_dir, ".cmake", "api", "v1")
cmake_api_query_dir = os.path.join(cmake_api_dir, "query")
cmake_api_reply_dir = os.path.join(cmake_api_dir, "reply")
query_file = os.path.join(cmake_api_query_dir, "codemodel-v2")
if not os.path.isfile(query_file):
os.makedirs(os.path.dirname(query_file))
open(query_file, "a").close() # create an empty file
if not is_proper_idf_project():
create_default_project_files()
if is_cmake_reconfigure_required(cmake_api_reply_dir):
run_cmake(src_dir, build_dir, extra_args)
if not os.path.isdir(cmake_api_reply_dir) or not os.listdir(cmake_api_reply_dir):
sys.stderr.write("Error: Couldn't find CMake API response file\n")
env.Exit(1)
codemodel = {}
for target in os.listdir(cmake_api_reply_dir):
if target.startswith("codemodel-v2"):
with open(os.path.join(cmake_api_reply_dir, target), "r") as fp:
codemodel = json.load(fp)
assert codemodel["version"]["major"] == 2
return codemodel
def populate_idf_env_vars(idf_env):
idf_env["IDF_PATH"] = fs.to_unix_path(FRAMEWORK_DIR)
additional_packages = [
os.path.join(TOOLCHAIN_DIR, "bin"),
platform.get_package_dir("tool-ninja"),
os.path.join(platform.get_package_dir("tool-cmake"), "bin"),
os.path.dirname(get_python_exe()),
]
idf_env["PATH"] = os.pathsep.join(additional_packages + [idf_env["PATH"]])
# Some users reported that the `IDF_TOOLS_PATH` var can seep into the
# underlying build system. Unsetting it is a safe workaround.
if "IDF_TOOLS_PATH" in idf_env:
del idf_env["IDF_TOOLS_PATH"]
def get_target_config(project_configs, target_index, cmake_api_reply_dir):
target_json = project_configs.get("targets")[target_index].get("jsonFile", "")
target_config_file = os.path.join(cmake_api_reply_dir, target_json)
if not os.path.isfile(target_config_file):
sys.stderr.write("Error: Couldn't find target config %s\n" % target_json)
env.Exit(1)
with open(target_config_file) as fp:
return json.load(fp)
def load_target_configurations(cmake_codemodel, cmake_api_reply_dir):
configs = {}
project_configs = cmake_codemodel.get("configurations")[0]
for config in project_configs.get("projects", []):
for target_index in config.get("targetIndexes", []):
target_config = get_target_config(
project_configs, target_index, cmake_api_reply_dir
)
configs[target_config["name"]] = target_config
return configs
def build_library(
default_env, lib_config, project_src_dir, prepend_dir=None, debug_allowed=True
):
lib_name = lib_config["nameOnDisk"]
lib_path = lib_config["paths"]["build"]
if prepend_dir:
lib_path = os.path.join(prepend_dir, lib_path)
lib_objects = compile_source_files(
lib_config, default_env, project_src_dir, prepend_dir, debug_allowed
)
return default_env.Library(
target=os.path.join("$BUILD_DIR", lib_path, lib_name), source=lib_objects
)
def get_app_includes(app_config):
plain_includes = []
sys_includes = []
cg = app_config["compileGroups"][0]
for inc in cg.get("includes", []):
inc_path = inc["path"]
if inc.get("isSystem", False):
sys_includes.append(inc_path)
else:
plain_includes.append(inc_path)
return {"plain_includes": plain_includes, "sys_includes": sys_includes}
def extract_defines(compile_group):
def _normalize_define(define_string):
define_string = define_string.strip()
if "=" in define_string:
define, value = define_string.split("=", maxsplit=1)
if any(char in value for char in (' ', '<', '>')):
value = f'"{value}"'
elif '"' in value and not value.startswith("\\"):
value = value.replace('"', '\\"')
return (define, value)
return define_string
result = [
_normalize_define(d.get("define", ""))
for d in compile_group.get("defines", []) if d
]
for f in compile_group.get("compileCommandFragments", []):
fragment = f.get("fragment", "").strip()
if fragment.startswith('"'):
fragment = fragment.strip('"')
if fragment.startswith("-D"):
result.append(_normalize_define(fragment[2:]))
return result
def get_app_defines(app_config):
return extract_defines(app_config["compileGroups"][0])
def extract_link_args(target_config):
def _add_to_libpath(lib_path, link_args):
if lib_path not in link_args["LIBPATH"]:
link_args["LIBPATH"].append(lib_path)
def _add_archive(archive_path, link_args):
archive_name = os.path.basename(archive_path)
if archive_name not in link_args["LIBS"]:
_add_to_libpath(os.path.dirname(archive_path), link_args)
link_args["LIBS"].append(archive_name)
link_args = {"LINKFLAGS": [], "LIBS": [], "LIBPATH": [], "__LIB_DEPS": []}
for f in target_config.get("link", {}).get("commandFragments", []):
fragment = f.get("fragment", "").strip()
fragment_role = f.get("role", "").strip()
if not fragment or not fragment_role:
continue
args = click.parser.split_arg_string(fragment)
if fragment_role == "flags":
link_args["LINKFLAGS"].extend(args)
elif fragment_role in ("libraries", "libraryPath"):
if fragment.startswith("-l"):
link_args["LIBS"].extend(args)
elif fragment.startswith("-L"):
lib_path = fragment.replace("-L", "").strip(" '\"")
_add_to_libpath(lib_path, link_args)
elif fragment.startswith("-") and not fragment.startswith("-l"):
# CMake mistakenly marks LINKFLAGS as libraries
link_args["LINKFLAGS"].extend(args)
elif fragment.endswith(".a"):
archive_path = fragment
# process static archives
if os.path.isabs(archive_path):
# In case of precompiled archives
_add_archive(archive_path, link_args)
else:
# In case of archives within project
if archive_path.startswith(".."):
# Precompiled archives from project component
_add_archive(
os.path.normpath(os.path.join(BUILD_DIR, archive_path)),
link_args,
)
else:
# Internally built libraries used for dependency resolution
link_args["__LIB_DEPS"].append(os.path.basename(archive_path))
return link_args
def filter_args(args, allowed, ignore=None):
if not allowed:
return []
ignore = ignore or []
result = []
i = 0
length = len(args)
while i < length:
if any(args[i].startswith(f) for f in allowed) and not any(
args[i].startswith(f) for f in ignore
):
result.append(args[i])
if i + 1 < length and not args[i + 1].startswith("-"):
i += 1
result.append(args[i])
i += 1
return result
def get_app_flags(app_config, default_config):
def _extract_flags(config):
flags = {}
for cg in config["compileGroups"]:
flags[cg["language"]] = []
for ccfragment in cg["compileCommandFragments"]:
fragment = ccfragment.get("fragment", "").strip("\" ")
if not fragment or fragment.startswith("-D"):
continue
flags[cg["language"]].extend(
click.parser.split_arg_string(fragment.strip())
)
return flags
app_flags = _extract_flags(app_config)
default_flags = _extract_flags(default_config)
# Flags are sorted because CMake randomly populates build flags in code model
return {
"ASPPFLAGS": sorted(app_flags.get("ASM", default_flags.get("ASM"))),
"CFLAGS": sorted(app_flags.get("C", default_flags.get("C"))),
"CXXFLAGS": sorted(app_flags.get("CXX", default_flags.get("CXX"))),
}
def get_sdk_configuration():
config_path = os.path.join(BUILD_DIR, "config", "sdkconfig.json")
if not os.path.isfile(config_path):
print('Warning: Could not find "sdkconfig.json" file\n')
try:
with open(config_path, "r") as fp:
return json.load(fp)
except:
return {}
def load_component_paths(framework_components_dir, ignored_component_prefixes=None):
def _scan_components_from_framework():
result = []
for component in os.listdir(framework_components_dir):
component_path = os.path.join(framework_components_dir, component)
if component.startswith(ignored_component_prefixes) or not os.path.isdir(
component_path
):
continue
result.append(component_path)
return result
# First of all, try to load the list of used components from the project description
components = []
ignored_component_prefixes = ignored_component_prefixes or []
project_description_file = os.path.join(BUILD_DIR, "project_description.json")
if os.path.isfile(project_description_file):
with open(project_description_file) as fp:
try:
data = json.load(fp)
for path in data.get("build_component_paths", []):
if not os.path.basename(path).startswith(
ignored_component_prefixes
):
components.append(path)
except:
print(
"Warning: Could not find load components from project description!\n"
)
return components or _scan_components_from_framework()
def extract_linker_script_fragments_backup(framework_components_dir, sdk_config):
# Hardware-specific components are excluded from search and added manually below
project_components = load_component_paths(
framework_components_dir, ignored_component_prefixes=("esp32", "riscv")
)
result = []
for component_path in project_components:
linker_fragment = os.path.join(component_path, "linker.lf")
if os.path.isfile(linker_fragment):
result.append(linker_fragment)
if not result:
sys.stderr.write("Error: Failed to extract paths to linker script fragments\n")
env.Exit(1)
if mcu not in ("esp32", "esp32s2", "esp32s3"):
result.append(os.path.join(framework_components_dir, "riscv", "linker.lf"))
# Add extra linker fragments
for fragment in (
os.path.join("esp_system", "app.lf"),
os.path.join("esp_common", "common.lf"),
os.path.join("esp_common", "soc.lf"),
os.path.join("newlib", "system_libs.lf"),
os.path.join("newlib", "newlib.lf"),
):
result.append(os.path.join(framework_components_dir, fragment))
if sdk_config.get("SPIRAM_CACHE_WORKAROUND", False):
result.append(
os.path.join(
framework_components_dir, "newlib", "esp32-spiram-rom-functions-c.lf"
)
)
if board.get("build.esp-idf.extra_lf_files", ""):
result.extend(
[
lf if os.path.isabs(lf) else os.path.join(PROJECT_DIR, lf)
for lf in board.get("build.esp-idf.extra_lf_files").splitlines()
if lf.strip()
]
)
return result
def extract_linker_script_fragments(
ninja_buildfile, framework_components_dir, sdk_config
):
def _normalize_fragment_path(base_dir, fragment_path):
if not os.path.isabs(fragment_path):
fragment_path = os.path.abspath(
os.path.join(base_dir, fragment_path)
)
if not os.path.isfile(fragment_path):
print("Warning! The `%s` fragment is not found!" % fragment_path)
return fragment_path
assert os.path.isfile(
ninja_buildfile
), "Cannot extract linker fragments! Ninja build file is missing!"
result = []
with open(ninja_buildfile, encoding="utf8") as fp:
for line in fp.readlines():
if "sections.ld: CUSTOM_COMMAND" not in line:
continue
for fragment_match in re.finditer(r"(\S+\.lf\b)+", line):
result.append(_normalize_fragment_path(
BUILD_DIR, fragment_match.group(0).replace("$:", ":")
))
break
# Fall back option if the new algorithm didn't work
if not result:
result = extract_linker_script_fragments_backup(
framework_components_dir, sdk_config
)
if board.get("build.esp-idf.extra_lf_files", ""):
for fragment_path in board.get(
"build.esp-idf.extra_lf_files"
).splitlines():
if not fragment_path.strip():
continue
result.append(_normalize_fragment_path(PROJECT_DIR, fragment_path))
return result
def create_custom_libraries_list(ldgen_libraries_file, ignore_targets):
if not os.path.isfile(ldgen_libraries_file):
sys.stderr.write("Error: Couldn't find the list of framework libraries\n")
env.Exit(1)
pio_libraries_file = ldgen_libraries_file + "_pio"
if os.path.isfile(pio_libraries_file):
return pio_libraries_file
lib_paths = []
with open(ldgen_libraries_file, "r") as fp:
lib_paths = fp.readlines()
with open(pio_libraries_file, "w") as fp:
for lib_path in lib_paths:
if all(
"lib%s.a" % t.replace("__idf_", "") not in lib_path
for t in ignore_targets
):
fp.write(lib_path)
return pio_libraries_file
def generate_project_ld_script(sdk_config, ignore_targets=None):
ignore_targets = ignore_targets or []
linker_script_fragments = extract_linker_script_fragments(
os.path.join(BUILD_DIR, "build.ninja"),
os.path.join(FRAMEWORK_DIR, "components"),
sdk_config
)
# Create a new file to avoid automatically generated library entry as files
# from this library are built internally by PlatformIO
libraries_list = create_custom_libraries_list(
os.path.join(BUILD_DIR, "ldgen_libraries"), ignore_targets
)
args = {
"script": os.path.join(FRAMEWORK_DIR, "tools", "ldgen", "ldgen.py"),
"config": SDKCONFIG_PATH,
"fragments": " ".join(
['"%s"' % fs.to_unix_path(f) for f in linker_script_fragments]
),
"kconfig": os.path.join(FRAMEWORK_DIR, "Kconfig"),
"env_file": os.path.join("$BUILD_DIR", "config.env"),
"libraries_list": libraries_list,
"objdump": os.path.join(
TOOLCHAIN_DIR,
"bin",
env.subst("$CC").replace("-gcc", "-objdump"),
),
}
cmd = (
'"$ESPIDF_PYTHONEXE" "{script}" --input $SOURCE '
'--config "{config}" --fragments {fragments} --output $TARGET '
'--kconfig "{kconfig}" --env-file "{env_file}" '
'--libraries-file "{libraries_list}" '
'--objdump "{objdump}"'
).format(**args)
initial_ld_script = os.path.join(
FRAMEWORK_DIR,
"components",
"esp_system",
"ld",
idf_variant,
"sections.ld.in",
)
framework_version = [int(v) for v in get_framework_version().split(".")]
if framework_version[:2] > [5, 2]:
initial_ld_script = preprocess_linker_file(
initial_ld_script,
os.path.join(
BUILD_DIR,
"esp-idf",
"esp_system",
"ld",
"sections.ld.in",
)
)
return env.Command(
os.path.join("$BUILD_DIR", "sections.ld"),
initial_ld_script,
env.VerboseAction(cmd, "Generating project linker script $TARGET"),
)
# A temporary workaround to avoid modifying CMake mainly for the "heap" library.
# The "tlsf.c" source file in this library has an include flag relative
# to CMAKE_CURRENT_SOURCE_DIR which breaks PlatformIO builds that have a
# different working directory
def _fix_component_relative_include(config, build_flags, source_index):
source_file_path = config["sources"][source_index]["path"]
build_flags = build_flags.replace("..", os.path.dirname(source_file_path) + "/..")
return build_flags
def prepare_build_envs(config, default_env, debug_allowed=True):
build_envs = []
target_compile_groups = config.get("compileGroups", [])
if not target_compile_groups:
print("Warning! The `%s` component doesn't register any source files. "
"Check if sources are set in component's CMakeLists.txt!" % config["name"]
)
is_build_type_debug = "debug" in env.GetBuildType() and debug_allowed
for cg in target_compile_groups:
includes = []
sys_includes = []
for inc in cg.get("includes", []):
inc_path = inc["path"]
if inc.get("isSystem", False):
sys_includes.append(inc_path)
else:
includes.append(inc_path)
defines = extract_defines(cg)
compile_commands = cg.get("compileCommandFragments", [])
build_env = default_env.Clone()
build_env.SetOption("implicit_cache", 1)
for cc in compile_commands:
build_flags = cc.get("fragment", "").strip("\" ")
if not build_flags.startswith("-D"):
if build_flags.startswith("-include") and ".." in build_flags:
source_index = cg.get("sourceIndexes")[0]
build_flags = _fix_component_relative_include(
config, build_flags, source_index)
parsed_flags = build_env.ParseFlags(build_flags)
build_env.AppendUnique(**parsed_flags)
if cg.get("language", "") == "ASM":
build_env.AppendUnique(ASPPFLAGS=parsed_flags.get("CCFLAGS", []))
build_env.AppendUnique(CPPDEFINES=defines, CPPPATH=includes)
if sys_includes:
build_env.Append(CCFLAGS=[("-isystem", inc) for inc in sys_includes])
build_env.ProcessUnFlags(default_env.get("BUILD_UNFLAGS"))
if is_build_type_debug:
build_env.ConfigureDebugFlags()
build_envs.append(build_env)
return build_envs
def compile_source_files(
config, default_env, project_src_dir, prepend_dir=None, debug_allowed=True
):
build_envs = prepare_build_envs(config, default_env, debug_allowed)
objects = []
components_dir = fs.to_unix_path(os.path.join(FRAMEWORK_DIR, "components"))
for source in config.get("sources", []):
if source["path"].endswith(".rule"):
continue
compile_group_idx = source.get("compileGroupIndex")
if compile_group_idx is not None:
src_dir = config["paths"]["source"]
if not os.path.isabs(src_dir):
src_dir = os.path.join(project_src_dir, config["paths"]["source"])
src_path = source.get("path")
if not os.path.isabs(src_path):
# For cases when sources are located near CMakeLists.txt
src_path = os.path.join(project_src_dir, src_path)
obj_path = os.path.join("$BUILD_DIR", prepend_dir or "")
if src_path.lower().startswith(components_dir.lower()):
obj_path = os.path.join(
obj_path, os.path.relpath(src_path, components_dir)
)
else:
if not os.path.isabs(source["path"]):
obj_path = os.path.join(obj_path, source["path"])
else:
obj_path = os.path.join(obj_path, os.path.basename(src_path))
preserve_source_file_extension = board.get(
"build.esp-idf.preserve_source_file_extension", "yes"
) == "yes"
objects.append(
build_envs[compile_group_idx].StaticObject(
target=(
obj_path
if preserve_source_file_extension
else os.path.splitext(obj_path)[0]
) + ".o",
source=os.path.realpath(src_path),
)
)
return objects
def run_tool(cmd):
idf_env = os.environ.copy()
populate_idf_env_vars(idf_env)
result = exec_command(cmd, env=idf_env)
if result["returncode"] != 0:
sys.stderr.write(result["out"] + "\n")
sys.stderr.write(result["err"] + "\n")
env.Exit(1)
if int(ARGUMENTS.get("PIOVERBOSE", 0)):
print(result["out"])
print(result["err"])
def RunMenuconfig(target, source, env):
idf_env = os.environ.copy()
populate_idf_env_vars(idf_env)
rc = subprocess.call(
[
os.path.join(platform.get_package_dir("tool-cmake"), "bin", "cmake"),
"--build",
BUILD_DIR,
"--target",
"menuconfig",
],
env=idf_env,
)
if rc != 0:
sys.stderr.write("Error: Couldn't execute 'menuconfig' target.\n")
env.Exit(1)
def run_cmake(src_dir, build_dir, extra_args=None):
cmd = [
os.path.join(platform.get_package_dir("tool-cmake") or "", "bin", "cmake"),
"-S",
src_dir,
"-B",
build_dir,
"-G",
"Ninja",
]
if extra_args:
cmd.extend(extra_args)
run_tool(cmd)
def find_lib_deps(components_map, elf_config, link_args, ignore_components=None):
ignore_components = ignore_components or []
result = [
components_map[d["id"]]["lib"]
for d in elf_config.get("dependencies", [])
if components_map.get(d["id"], {})
and not d["id"].startswith(tuple(ignore_components))
]
implicit_lib_deps = link_args.get("__LIB_DEPS", [])
for component in components_map.values():
component_config = component["config"]
if (
component_config["type"] not in ("STATIC_LIBRARY", "OBJECT_LIBRARY")
or component_config["name"] in ignore_components
):
continue
if (
component_config["nameOnDisk"] in implicit_lib_deps
and component["lib"] not in result
):
result.append(component["lib"])
return result
def build_bootloader(sdk_config):
bootloader_src_dir = os.path.join(
FRAMEWORK_DIR, "components", "bootloader", "subproject"
)
code_model = get_cmake_code_model(
bootloader_src_dir,
os.path.join(BUILD_DIR, "bootloader"),
[
"-DIDF_TARGET=" + idf_variant,
"-DPYTHON_DEPS_CHECKED=1",
"-DPYTHON=" + get_python_exe(),
"-DIDF_PATH=" + FRAMEWORK_DIR,
"-DSDKCONFIG=" + SDKCONFIG_PATH,
"-DPROJECT_SOURCE_DIR=" + PROJECT_DIR,
"-DLEGACY_INCLUDE_COMMON_HEADERS=",
"-DEXTRA_COMPONENT_DIRS="
+ os.path.join(FRAMEWORK_DIR, "components", "bootloader"),
],
)
if not code_model:
sys.stderr.write("Error: Couldn't find code model for bootloader\n")
env.Exit(1)
target_configs = load_target_configurations(
code_model,
os.path.join(BUILD_DIR, "bootloader", ".cmake", "api", "v1", "reply"),
)
elf_config = get_project_elf(target_configs)
if not elf_config:
sys.stderr.write(
"Error: Couldn't load the main firmware target of the project\n"
)
env.Exit(1)
bootloader_env = env.Clone()
components_map = get_components_map(
target_configs, ["STATIC_LIBRARY", "OBJECT_LIBRARY"]
)
# Note: By default the size of bootloader is limited to 0x2000 bytes,
# in debug mode the footprint size can be easily grow beyond this limit
build_components(
bootloader_env,
components_map,
bootloader_src_dir,
"bootloader",
debug_allowed=sdk_config.get("BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG", False),
)
link_args = extract_link_args(elf_config)
extra_flags = filter_args(link_args["LINKFLAGS"], ["-T", "-u"])
link_args["LINKFLAGS"] = sorted(
list(set(link_args["LINKFLAGS"]) - set(extra_flags))
)
bootloader_env.MergeFlags(link_args)
bootloader_env.Append(LINKFLAGS=extra_flags)
bootloader_libs = find_lib_deps(components_map, elf_config, link_args)
bootloader_env.Prepend(__RPATH="-Wl,--start-group ")
bootloader_env.Append(
CPPDEFINES=["__BOOTLOADER_BUILD"], _LIBDIRFLAGS=" -Wl,--end-group"
)
return bootloader_env.ElfToBin(
os.path.join("$BUILD_DIR", "bootloader"),
bootloader_env.Program(
os.path.join("$BUILD_DIR", "bootloader.elf"), bootloader_libs
),
)
def get_targets_by_type(target_configs, target_types, ignore_targets=None):
ignore_targets = ignore_targets or []
result = []
for target_config in target_configs.values():
if (
target_config["type"] in target_types
and target_config["name"] not in ignore_targets
):
result.append(target_config)
return result
def get_components_map(target_configs, target_types, ignore_components=None):
result = {}
for config in get_targets_by_type(target_configs, target_types, ignore_components):
if "nameOnDisk" not in config:
config["nameOnDisk"] = "lib%s.a" % config["name"]
result[config["id"]] = {"config": config}
return result
def build_components(
env, components_map, project_src_dir, prepend_dir=None, debug_allowed=True
):
for k, v in components_map.items():
components_map[k]["lib"] = build_library(
env, v["config"], project_src_dir, prepend_dir, debug_allowed
)
def get_project_elf(target_configs):
exec_targets = get_targets_by_type(target_configs, ["EXECUTABLE"])
if len(exec_targets) > 1:
print(
"Warning: Multiple elf targets found. The %s will be used!"
% exec_targets[0]["name"]
)
return exec_targets[0]
def generate_default_component():
# Used to force CMake generate build environments for all supported languages
prj_cmake_tpl = """# Warning! Do not delete this auto-generated file.
file(GLOB component_sources *.c* *.S)
idf_component_register(SRCS ${component_sources})
"""
dummy_component_path = os.path.join(FRAMEWORK_DIR, "components", "__pio_env")
if os.path.isdir(dummy_component_path):
return
os.makedirs(dummy_component_path)
for ext in (".cpp", ".c", ".S"):
dummy_file = os.path.join(dummy_component_path, "__dummy" + ext)
if not os.path.isfile(dummy_file):
open(dummy_file, "a").close()
component_cmake = os.path.join(dummy_component_path, "CMakeLists.txt")
if not os.path.isfile(component_cmake):
with open(component_cmake, "w") as fp:
fp.write(prj_cmake_tpl)
def find_default_component(target_configs):
for config in target_configs:
if "__pio_env" in config:
return config
sys.stderr.write(
"Error! Failed to find the default IDF component with build information for "