ArduPilot之开源代码waf编译

2023-12-23 19:14:19

1. 源由

关于Ardupilot的固件编译步骤介绍,已经在前面整理了一些资料:

【1】ArduPilot开源代码之H743+BMI270x2+ChibiOS配置适配
【2】ArduPilot飞控AOCODARC-H7DUAL固件编译

但是Ardupilot执行编译的框架是通过waf这个软件来集成的。waf与传统Makefile是如何一起协作的?

对于ChibiOS目标飞控板,代码编译的整个过程,waf是如何整合在一起,目前来说,还有点模模糊糊的。对于后续要深入后续ChibiOS移植就需要了解整个过程,以便在移植过程中出现需要改动的脚本、目录、代码等方面的内容。

2. 编译过程

2.1 代码同步

$ ./Tools/gittools/submodule-sync.sh

注:代码同步与waf没什么关系,这里仅仅使用的bash脚本,不再展开分析。

2.2 编译bootloader

$ ./Tools/scripts/build_bootloaders.py Aocoda-RC-H743Dual

注:Ardupilot的bootloader实际在PR过程中发现,不仅仅需要提供目标板配置文件,还需要上传bootloader二进制;通过两个commit来处理目标板配置代码和二进制bootloader。

  1. Add Aocoda-RC-H743Dual target board configuration #25396
  2. Add Aocoda-RC H743Dual board #5592
  3. AP_Bootloader: Fix AIRVOLUTE format issue #25401
  4. AP_Bootloader: Reserve Aocoda-RC board IDs and apply for H743DUAL/F405V3 #25402

2.3 配置单板

$ ./waf configure --board Aocoda-RC-H743Dual

2.4 固件编译、链接

$ ./waf plane

3. 编译bootloader

3.1 命令帮助

./Tools/scripts/build_bootloaders.py -h
usage: build_bootloaders.py [-h] [--signing-key SIGNING_KEY] [--debug]
                            [--periph-only]
                            pattern

make_secure_bl

positional arguments:
  pattern               board wildcard pattern

optional arguments:
  -h, --help            show this help message and exit
  --signing-key SIGNING_KEY
                        signing key for secure bootloader
  --debug               build with debug symbols
  --periph-only         only build AP_Periph boards

3.2 python脚本

重要函数如下:

  • read_hwdef
  • is_ap_periph
  • get_board_list
  • run_program
  • build_board
./Tools/scripts/build_bootloaders.py
 └──> ./Tools/scripts/signing/make_secure_bl.py

3.3 脚本分析

通过脚本分析可以看出,编译bootloader最终执行的还是waf命令:

  • ./waf configure --board Aocoda-RC-H743Dual --bootloader --no-submodule-update --Werror
  • ./waf clean
  • ./waf bootloader
./Tools/scripts/build_bootloaders.py
 ├──> <secure bootloader check>
 │   └──> [prevent the easy mistake of using private key] return
 ├──> <for board in get_board_list()>
 │   └──> <board match>
 │       ├──> build_board
 │       │   ├──> run_program(["./waf", "configure"] + configure_args): fail return false;
 │       │   ├──> run_program(["./waf", "clean"]): fail return false;
 │       │   └──> run_program(["./waf", "bootloader"]): fail return false;
 │       ├──> <failed build>
 │       │   ├──> add to fail log
 │       │   └──> continue
 │       ├──> [Create bootloader bin file]
 │       ├──> [Create bootloader elf file]
 │       ├──> [Create bootloader hex file]
 │       └──> <secure bootloader>
 │           ├──> [Create bootloader secure bin file]
 │           └──> [Create bootloader secure elf file]
 └──> [Failed boards summary]

4. waf脚本

4.1 命令帮助

  • [Ardupilot] waf-light帮助
$ ./waf-light --help
waf [commands] [options]

Main commands (example: ./waf build -j4)
  AP_Periph     : builds AP_Periph programs
  all           : builds all programs of all group
  antennatracker: builds antennatracker programs
  benchmarks    : builds all programs of benchmarks group
  bin           : builds all programs of bin group
  blimp         : builds blimp programs
  bootloader    : builds bootloader programs
  build         : executes the build
  check         : builds all programs and run tests
  check-all     : shortcut for `waf check --alltests`
  clean         : cleans the project
  conf          :
        Decorator: attach new configuration functions to :py:class:`waflib.Build.BuildContext` and
        :py:class:`waflib.Configure.ConfigurationContext`. The methods bound will accept a parameter
        named 'mandatory' to disable the configuration errors::

                def configure(conf):
                        conf.find_program('abc', mandatory=False)

        :param f: method to bind
        :type f: function

  configure     : configures the project
  copter        : builds copter programs
  dist          : makes a tarball for redistributing the sources
  distcheck     : checks if the project compiles (tarball from 'dist')
  distclean     : removes build folders and data
  examples      : builds all programs of examples group
  heli          : builds heli programs
  install       : installs the targets on the system
  iofirmware    : builds iofirmware programs
  list          : lists the targets to execute
  localinstall  : runs install using BLD/install as destdir, where BLD is the build variant directory
  plane         : builds plane programs
  replay        : builds replay programs
  rover         : builds rover programs
  rsync         : runs localinstall and then rsyncs BLD/install with the target system
  step          : executes tasks in a step-by-step fashion, for debugging
  sub           : builds sub programs
  tests         : builds all programs of tests group
  tool          : builds all programs of tool group
  uninstall     : removes the targets installed

Options:
  --version             show program's version number and exit
  -c COLORS, --color=COLORS
                        whether to use colors (yes/no/auto) [default: auto]
  -j JOBS, --jobs=JOBS  amount of parallel jobs (2)
  -k, --keep            continue despite errors (-kk to try harder)
  -v, --verbose         verbosity level -v -vv or -vvv [default: 0]
  --zones=ZONES         debugging zones (task_gen, deps, tasks, etc)
  -h, --help            show this help message and exit
  --notests             Exec no unit tests
  --alltests            Exec all unit tests
  --clear-failed        Force failed unit tests to run again next time
  --testcmd=TESTCMD     Run the unit tests using the test-cmd string example "--testcmd="valgrind --error-exitcode=1 %s" to run under valgrind
  --dump-test-scripts   Create python scripts to help debug tests

  Configuration options:
    -o OUT, --out=OUT   build dir for the project
    -t TOP, --top=TOP   src dir for the project
    --check-cxx-compiler=CHECK_CXX_COMPILER
                        list of C++ compilers to try [g++ clang++ icpc]
    --check-c-compiler=CHECK_C_COMPILER
                        list of C compilers to try [gcc clang icc]

  Build and installation options:
    -p, --progress      -p: progress bar; -pp: ide output
    --targets=TARGETS   task generators, e.g. "target1,target2"

  Step options:
    --files=FILES       files to process, by regexp, e.g. "*/main.c,*/test/main.o"

  Installation and uninstallation options:
    -f, --force         force file installation
    --distcheck-args=ARGS
                        arguments to pass to distcheck

  Python Options:
    --nopyc             Do not install bytecode compiled .pyc files (configuration) [Default:install]
    --nopyo             Do not install optimised compiled .pyo files (configuration) [Default:install]
    --nopycache         Do not use __pycache__ directory to install objects [Default:auto]
    --python=PYTHON     python binary to be used [Default: /usr/bin/python3]
    --pythondir=PYTHONDIR
                        Installation path for python modules (py, platform-independent .py and .pyc files)
    --pythonarchdir=PYTHONARCHDIR
                        Installation path for python extension (pyext, platform-dependent .so or .dylib files)

  Ardupilot configure options:
    --board=BOARD       Target board to build, choices are ACNS-CM4Pilot, ACNS-F405AIO, aero, AeroFox-Airspeed, AeroFox-Airspeed-DLVR, AeroFox-GNSS_F9P, AeroFox-PMU,
                        airbotf4, AIRLink, Airvolute-DCS2, Aocoda-RC-H743Dual, AR-F407SmartBat, ARK_CANNODE, ARK_GPS, ARK_RTK_GPS, ARKV6X, AtomRCF405NAVI, bbbmini,
                        BeastF7, BeastF7v2, BeastH7, BeastH7v2, bebop, BETAFPV-F405, bhat, BirdCANdy, BlitzF745AIO, blue, C-RTK2-HP, canzero, CarbonixF405,
                        CarbonixL496, crazyflie2, CUAV-Nora, CUAV-Nora-bdshot, CUAV-X7, CUAV-X7-bdshot, CUAV_GPS, CUAVv5, CUAVv5-bdshot, CUAVv5Nano, CUAVv5Nano-bdshot,
                        CubeBlack, CubeBlack+, CubeBlack-periph, CubeGreen-solo, CubeOrange, CubeOrange-bdshot, CubeOrange-joey, CubeOrange-ODID, CubeOrange-periph,
                        CubeOrange-periph-heavy, CubeOrange-SimOnHardWare, CubeOrangePlus, CubeOrangePlus-bdshot, CubeOrangePlus-SimOnHardWare, CubePilot-CANMod,
                        CubePurple, CubeRedPrimary, CubeRedSecondary, CubeSolo, CubeYellow, CubeYellow-bdshot, dark, DevEBoxH7v2, disco, DrotekP3Pro, Durandal,
                        Durandal-bdshot, edge, erleboard, erlebrain2, esp32buzz, esp32diy, esp32empty, esp32icarus, esp32nick, esp32s3devkit, esp32tomte76, f103-ADSB,
                        f103-Airspeed, f103-GPS, f103-HWESC, f103-QiotekPeriph, f103-RangeFinder, f103-Trigger, f303-GPS, f303-HWESC, f303-M10025, f303-M10070,
                        f303-MatekGPS, f303-PWM, f303-TempSensor, f303-Universal, F35Lightning, f405-MatekAirspeed, f405-MatekGPS, F4BY, FlyingMoonF407, FlyingMoonF427,
                        FlyingMoonH743, FlywooF405Pro, FlywooF405S-AIO, FlywooF745, FlywooF745Nano, fmuv2, fmuv3, fmuv3-bdshot, fmuv5, FoxeerH743v1, FreeflyRTK, G4-ESC,
                        H743_BMI270x2_v30, H757I_EVAL, H757I_EVAL_intf, HEEWING-F405, HEEWING-F405v2, Here4AP, HerePro, Hitec-Airspeed, HitecMosaic, HolybroG4_Compass,
                        HolybroG4_GPS, HolybroGPS, iomcu, iomcu-dshot, iomcu-f103, iomcu-f103-dshot, iomcu_f103_8MHz, JFB100, JFB110, JHEMCU-GSF405A, JHEMCU-
                        GSF405A-RX2, KakuteF4, KakuteF4Mini, KakuteF7, KakuteF7-bdshot, KakuteF7Mini, KakuteH7, KakuteH7-bdshot, KakuteH7-Wing, KakuteH7Mini,
                        KakuteH7Mini-Nand, KakuteH7v2, kha_eth, linux, luminousbee4, luminousbee5, MambaF405-2022, MambaF405US-I2C, MambaF405v2, MambaH743v4, MatekF405,
                        MatekF405-bdshot, MatekF405-CAN, MatekF405-STD, MatekF405-TE, MatekF405-TE-bdshot, MatekF405-Wing, MatekF405-Wing-bdshot, MatekF765-SE,
                        MatekF765-Wing, MatekF765-Wing-bdshot, MatekH743, MatekH743-bdshot, MatekH743-periph, MatekL431-ADSB, MatekL431-Airspeed, MatekL431-BattMon,
                        MatekL431-bdshot, MatekL431-DShot, MatekL431-EFI, MatekL431-GPS, MatekL431-HWTelem, MatekL431-Periph, MatekL431-Proximity,
                        MatekL431-Rangefinder, MatekL431-RC, MazzyStarDrone, mindpx-v2, mini-pix, modalai_fc-v1, mRo-M10095, mRoCANPWM-M10126, mRoControlZeroClassic,
                        mRoControlZeroF7, mRoControlZeroH7, mRoControlZeroH7-bdshot, mRoControlZeroOEMH7, mRoCZeroOEMH7-bdshot, mRoNexus, mRoPixracerPro,
                        mRoPixracerPro-bdshot, mRoX21, mRoX21-777, navigator, navio, navio2, Nucleo-G491, Nucleo-L476, Nucleo-L496, NucleoH743, NucleoH755, obal,
                        ocpoc_zynq, omnibusf4, omnibusf4pro, omnibusf4pro-bdshot, omnibusf4pro-one, omnibusf4v6, OMNIBUSF7V2, OmnibusNanoV6, OmnibusNanoV6-bdshot,
                        PH4-mini, PH4-mini-bdshot, Pix32v5, PixC4-Jetson, PixFlamingo, Pixhawk1, Pixhawk1-1M, Pixhawk1-1M-bdshot, Pixhawk1-bdshot, Pixhawk4,
                        Pixhawk4-bdshot, Pixhawk5X, Pixhawk6C, Pixhawk6C-bdshot, Pixhawk6X, Pixhawk6X-bdshot, Pixhawk6X-ODID, PixPilot-C3, PixPilot-V3, PixPilot-V6,
                        Pixracer, Pixracer-bdshot, Pixracer-periph, PixSurveyA1, PixSurveyA1-IND, PixSurveyA2, pocket, pxf, pxfmini, QioTekAdeptF407, QioTekZealotF427,
                        QioTekZealotH743, QioTekZealotH743-bdshot, R9Pilot, RADIX2HD, ReaperF745, revo-mini, revo-mini-bdshot, revo-mini-i2c, revo-mini-i2c-bdshot,
                        revo-mini-sd, rFCU, rGNSS, rst_zynq, SDMODELH7V1, Sierra-F405, Sierra-F412, Sierra-F9P, Sierra-L431, Sierra-PrecisionPoint, Sierra-TrueNavPro,
                        Sierra-TrueNorth, Sierra-TrueSpeed, sitl, SITL_arm_linux_gnueabihf, sitl_periph_gps, SITL_static, SITL_x86_64_linux_gnu, SIYI_N7, SkystarsH7HD,
                        SkystarsH7HD-bdshot, skyviper-f412-rev1, skyviper-journey, skyviper-v2450, sparky2, speedybeef4, SpeedyBeeF405Mini, SpeedyBeeF405WING,
                        speedybeef4v3, speedybeef4v4, SPRacingH7, SPRacingH7RF, SuccexF4, sw-nav-f405, sw-spar-f407, Swan-K1, TBS-Colibri-F7, thepeach-k1, thepeach-r1,
                        TMotorH743, vnav, VRBrain-v51, VRBrain-v52, VRBrain-v54, VRCore-v10, VRUBrain-v51, YJUAV_A6, YJUAV_A6SE, YJUAV_A6SE_H743, ZubaxGNSS, zynq.
    --debug             Configure as debug variant.
    -g, --debug-symbols
                        Add debug symbolds to build.
    --disable-watchdog  Build with watchdog disabled.
    --coverage          Configure coverage flags.
    --Werror            build with -Werror.
    --disable-Werror    Disable -Werror.
    --toolchain=TOOLCHAIN
                        Override default toolchain used for the board. Use "native" for using the host toolchain.
    --disable-gccdeps   Disable the use of GCC dependencies output method and use waf default method.
    --enable-asserts    enable OS level asserts.
    --save-temps        save compiler temporary files.
    --enable-malloc-guard
                        enable malloc guard regions.
    --enable-stats      enable OS level thread statistics.
    --bootloader        Configure for building a bootloader.
    --signed-fw         Configure for signed firmware support.
    --private-key=PRIVATE_KEY
                        path to private key for signing firmware.
    --no-autoconfig     Disable autoconfiguration feature. By default, the build system triggers a reconfiguration whenever it thinks it's necessary - this option
                        disables that.
    --no-submodule-update
                        Don't update git submodules. Useful for building with submodules at specific revisions.
    --enable-header-checks
                        Enable checking of headers
    --default-parameters=DEFAULT_PARAMETERS
                        set default parameters to embed in the firmware
    --enable-math-check-indexes
                        Enable checking of math indexes
    --disable-scripting
                        Disable onboard scripting engine
    --enable-scripting  Enable onboard scripting engine
    --no-gcs            Disable GCS code
    --scripting-checks  Enable runtime scripting sanity checks
    --enable-onvif      Enables and sets up ONVIF camera control
    --scripting-docs    enable generation of scripting documentation
    --enable-opendroneid
                        Enables OpenDroneID
    --enable-check-firmware
                        Enables firmware ID checking on boot
    --enable-custom-controller
                        Enables custom controller
    --enable-gps-logging
                        Enables GPS logging
    --enable-dds        Enable the dds client to connect with ROS2/DDS.
    --disable-networking
                        Disable the networking API code
    --enable-networking-tests
                        Enable the networking test code. Automatically enables networking.
    --enable-dronecan-tests
                        Enables DroneCAN tests in sitl

  Linux boards configure options:
    --prefix=PREFIX     installation prefix [default: '/usr/']
    --destdir=DESTDIR   installation root [default: '']
    --bindir=BINDIR     bindir
    --libdir=LIBDIR     libdir
    --apstatedir=APSTATEDIR
                        Where to save data like parameters, log and terrain. This is the --localstatedir + ArduPilots subdirectory [default: board-dependent, usually
                        /var/lib/ardupilot]
    --rsync-dest=RSYNC_DEST
                        Destination for the rsync Waf command. It can be passed during configuration in order to save typing.
    --enable-benchmarks
                        Enable benchmarks.
    --enable-lttng      Enable lttng integration
    --disable-libiio    Don't use libiio even if supported by board and dependencies available
    --disable-tests     Disable compilation and test execution
    --enable-sfml       Enable SFML graphics library
    --enable-sfml-joystick
                        Enable SFML joystick input library
    --enable-sfml-audio
                        Enable SFML audio library
    --osd               Enable OSD support
    --osd-fonts         Enable OSD support with fonts
    --sitl-osd          Enable SITL OSD
    --sitl-rgbled       Enable SITL RGBLed
    --force-32bit       Force 32bit build
    --build-dates       Include build date in binaries.  Appears in AUTOPILOT_VERSION.os_sw_version
    --sitl-flash-storage
                        Use flash storage emulation.
    --enable-ekf2       Configure with EKF2.
    --disable-ekf3      Configure without EKF3.
    --ekf-double        Configure EKF as double precision.
    --ekf-single        Configure EKF as single precision.
    --static            Force a static build
    --postype-single    force single precision postype_t
    --consistent-builds
                        force consistent build outputs for things like __LINE__
    --extra-hwdef=EXTRA_HWDEF
                        Extra hwdef.dat file for custom build.
    --assert-cc-version=ASSERT_CC_VERSION
                        fail configure if not using the specified gcc version
    --num-aux-imus=NUM_AUX_IMUS
                        number of auxiliary IMUs
    --board-start-time=BOARD_START_TIME
                        zero time on boot in microseconds

  Ardupilot build options:
    --program-group=PROGRAM_GROUP
                        Select all programs that go in <PROGRAM_GROUP>/ for the build. Example: `waf --program-group examples` builds all examples. The special group
                        "all" selects all programs.
    --upload            Upload applicable targets to a connected device. Not all platforms may support this. Example: `waf copter --upload` means "build arducopter and
                        upload it to my board".
    --upload-port=UPLOAD_PORT
                        Specify the port to be used with the --upload option. For example a port of /dev/ttyS10 indicates that serial port 10 shuld be used.
    --upload-force      Override board type check and continue loading. Same as using uploader.py --force.
    --summary-all       Print build summary for all targets. By default, only information about the first 20 targets will be printed.

  Ardupilot check options:
    --check-verbose     Output all test programs.
    --define=DEFINE     Add C++ define to build.

  Ardupilot clean options:
    --clean-all-sigs    Clean signatures for all tasks. By default, tasks that scan for implicit dependencies (like the compilation tasks) keep the dependency
                        information across clean commands, so that that information is changed only when really necessary. Also, some tasks that don't really produce
                        files persist their signature. This option avoids that behavior when cleaning the build.
    --asan              Build using the macOS clang Address Sanitizer. In order to run with Address Sanitizer support llvm-symbolizer is required to be on the PATH.
                        This option is only supported on macOS versions of clang.
    --ubsan             Build using the gcc undefined behaviour sanitizer
    --ubsan-abort       Build using the gcc undefined behaviour sanitizer and abort on error

4.2 [waf] waf-light帮助

$ ./waf-light --help
------> Executing code from the top-level wscript <-----
waf [commands] [options]

Main commands (example: ./waf build -j4)
  build    : executes the build
  clean    : cleans the project
  configure: configures the project
  dist     : makes a tarball for redistributing the sources
  distcheck: checks if the project compiles (tarball from 'dist')
  distclean: removes build folders and data
  install  : installs the targets on the system
  list     : lists the targets to execute
  step     : executes tasks in a step-by-step fashion, for debugging
  uninstall: removes the targets installed

Options:
  --version             show program's version number and exit
  -c COLORS, --color=COLORS
                        whether to use colors (yes/no/auto) [default: auto]
  -j JOBS, --jobs=JOBS  amount of parallel jobs (2)
  -k, --keep            continue despite errors (-kk to try harder)
  -v, --verbose         verbosity level -v -vv or -vvv [default: 0]
  --zones=ZONES         debugging zones (task_gen, deps, tasks, etc)
  -h, --help            show this help message and exit
  --make-waf            creates the waf script
  --interpreter=INTERPRETER
                        specify the #! line on top of the waf file
  --sign                make a signed file
  --zip-type=ZIP        specify the zip type [Allowed values: bz2 gz xz]
  --make-batch          creates a convenience waf.bat file (done automatically on win32 systems)
  --set-version=SETVER  sets the version number for waf releases (for the maintainer)
  --strip               shrinks waf (strip docstrings, saves 33kb)
  --nostrip             no shrinking
  --tools=ADD3RDPARTY   Comma-separated 3rd party tools to add, eg: "compat,ocaml" [Default: "compat15"]
  --coretools=CORETOOLS
                        Comma-separated core tools to add, eg: "vala,tex" [Default: all of them]
  --prelude=PRELUDE     Code to execute before calling waf
  --namesfrom=NAMESFROM
                        Obtain the file names from a model archive

  Configuration options:
    -o OUT, --out=OUT   build dir for the project
    -t TOP, --top=TOP   src dir for the project
    --prefix=PREFIX     installation prefix [default: '/usr/local/']
    --bindir=BINDIR     bindir
    --libdir=LIBDIR     libdir

  Build and installation options:
    -p, --progress      -p: progress bar; -pp: ide output
    --targets=TARGETS   task generators, e.g. "target1,target2"

  Step options:
    --files=FILES       files to process, by regexp, e.g. "*/main.c,*/test/main.o"

  Installation and uninstallation options:
    --destdir=DESTDIR   installation root [default: '']
    -f, --force         force file installation
    --distcheck-args=ARGS
                        arguments to pass to distcheck

  Python Options:
    --nopyc             Do not install bytecode compiled .pyc files (configuration) [Default:install]
    --nopyo             Do not install optimised compiled .pyo files (configuration) [Default:install]
    --nopycache         Do not use __pycache__ directory to install objects [Default:auto]
    --python=PYTHON     python binary to be used [Default: /usr/bin/python]
    --pythondir=PYTHONDIR
                        Installation path for python modules (py, platform-independent .py and .pyc files)
    --pythonarchdir=PYTHONARCHDIR
                        Installation path for python extension (pyext, platform-dependent .so or .dylib files)

4.3 Ardupilot v.s. waf 主要差异

4.3.1 命令差异

  1. AP_Periph
  2. all
  3. antennatracker
  4. benchmarks
  5. bin
  6. blimp
  7. bootloader
  8. check
  9. check-all
  10. conf
  11. copter
  12. examples
  13. heli
  14. iofirmware
  15. localinstall
  16. plane
  17. replay
  18. rover
  19. rsync
  20. sub
  21. tests
  22. tool

4.3.2 Ardupilot configure options

--board=BOARD       Target board to build, choices are ACNS-CM4Pilot, ACNS-F405AIO, aero, AeroFox-Airspeed, AeroFox-Airspeed-DLVR, AeroFox-GNSS_F9P, AeroFox-PMU,
                    airbotf4, AIRLink, Airvolute-DCS2, Aocoda-RC-H743Dual, AR-F407SmartBat, ARK_CANNODE, ARK_GPS, ARK_RTK_GPS, ARKV6X, AtomRCF405NAVI, bbbmini,
                    BeastF7, BeastF7v2, BeastH7, BeastH7v2, bebop, BETAFPV-F405, bhat, BirdCANdy, BlitzF745AIO, blue, C-RTK2-HP, canzero, CarbonixF405,
                    CarbonixL496, crazyflie2, CUAV-Nora, CUAV-Nora-bdshot, CUAV-X7, CUAV-X7-bdshot, CUAV_GPS, CUAVv5, CUAVv5-bdshot, CUAVv5Nano, CUAVv5Nano-bdshot,
                    CubeBlack, CubeBlack+, CubeBlack-periph, CubeGreen-solo, CubeOrange, CubeOrange-bdshot, CubeOrange-joey, CubeOrange-ODID, CubeOrange-periph,
                    CubeOrange-periph-heavy, CubeOrange-SimOnHardWare, CubeOrangePlus, CubeOrangePlus-bdshot, CubeOrangePlus-SimOnHardWare, CubePilot-CANMod,
                    CubePurple, CubeRedPrimary, CubeRedSecondary, CubeSolo, CubeYellow, CubeYellow-bdshot, dark, DevEBoxH7v2, disco, DrotekP3Pro, Durandal,
                    Durandal-bdshot, edge, erleboard, erlebrain2, esp32buzz, esp32diy, esp32empty, esp32icarus, esp32nick, esp32s3devkit, esp32tomte76, f103-ADSB,
                    f103-Airspeed, f103-GPS, f103-HWESC, f103-QiotekPeriph, f103-RangeFinder, f103-Trigger, f303-GPS, f303-HWESC, f303-M10025, f303-M10070,
                    f303-MatekGPS, f303-PWM, f303-TempSensor, f303-Universal, F35Lightning, f405-MatekAirspeed, f405-MatekGPS, F4BY, FlyingMoonF407, FlyingMoonF427,
                    FlyingMoonH743, FlywooF405Pro, FlywooF405S-AIO, FlywooF745, FlywooF745Nano, fmuv2, fmuv3, fmuv3-bdshot, fmuv5, FoxeerH743v1, FreeflyRTK, G4-ESC,
                    H743_BMI270x2_v30, H757I_EVAL, H757I_EVAL_intf, HEEWING-F405, HEEWING-F405v2, Here4AP, HerePro, Hitec-Airspeed, HitecMosaic, HolybroG4_Compass,
                    HolybroG4_GPS, HolybroGPS, iomcu, iomcu-dshot, iomcu-f103, iomcu-f103-dshot, iomcu_f103_8MHz, JFB100, JFB110, JHEMCU-GSF405A, JHEMCU-
                    GSF405A-RX2, KakuteF4, KakuteF4Mini, KakuteF7, KakuteF7-bdshot, KakuteF7Mini, KakuteH7, KakuteH7-bdshot, KakuteH7-Wing, KakuteH7Mini,
                    KakuteH7Mini-Nand, KakuteH7v2, kha_eth, linux, luminousbee4, luminousbee5, MambaF405-2022, MambaF405US-I2C, MambaF405v2, MambaH743v4, MatekF405,
                    MatekF405-bdshot, MatekF405-CAN, MatekF405-STD, MatekF405-TE, MatekF405-TE-bdshot, MatekF405-Wing, MatekF405-Wing-bdshot, MatekF765-SE,
                    MatekF765-Wing, MatekF765-Wing-bdshot, MatekH743, MatekH743-bdshot, MatekH743-periph, MatekL431-ADSB, MatekL431-Airspeed, MatekL431-BattMon,
                    MatekL431-bdshot, MatekL431-DShot, MatekL431-EFI, MatekL431-GPS, MatekL431-HWTelem, MatekL431-Periph, MatekL431-Proximity,
                    MatekL431-Rangefinder, MatekL431-RC, MazzyStarDrone, mindpx-v2, mini-pix, modalai_fc-v1, mRo-M10095, mRoCANPWM-M10126, mRoControlZeroClassic,
                    mRoControlZeroF7, mRoControlZeroH7, mRoControlZeroH7-bdshot, mRoControlZeroOEMH7, mRoCZeroOEMH7-bdshot, mRoNexus, mRoPixracerPro,
                    mRoPixracerPro-bdshot, mRoX21, mRoX21-777, navigator, navio, navio2, Nucleo-G491, Nucleo-L476, Nucleo-L496, NucleoH743, NucleoH755, obal,
                    ocpoc_zynq, omnibusf4, omnibusf4pro, omnibusf4pro-bdshot, omnibusf4pro-one, omnibusf4v6, OMNIBUSF7V2, OmnibusNanoV6, OmnibusNanoV6-bdshot,
                    PH4-mini, PH4-mini-bdshot, Pix32v5, PixC4-Jetson, PixFlamingo, Pixhawk1, Pixhawk1-1M, Pixhawk1-1M-bdshot, Pixhawk1-bdshot, Pixhawk4,
                    Pixhawk4-bdshot, Pixhawk5X, Pixhawk6C, Pixhawk6C-bdshot, Pixhawk6X, Pixhawk6X-bdshot, Pixhawk6X-ODID, PixPilot-C3, PixPilot-V3, PixPilot-V6,
                    Pixracer, Pixracer-bdshot, Pixracer-periph, PixSurveyA1, PixSurveyA1-IND, PixSurveyA2, pocket, pxf, pxfmini, QioTekAdeptF407, QioTekZealotF427,
                    QioTekZealotH743, QioTekZealotH743-bdshot, R9Pilot, RADIX2HD, ReaperF745, revo-mini, revo-mini-bdshot, revo-mini-i2c, revo-mini-i2c-bdshot,
                    revo-mini-sd, rFCU, rGNSS, rst_zynq, SDMODELH7V1, Sierra-F405, Sierra-F412, Sierra-F9P, Sierra-L431, Sierra-PrecisionPoint, Sierra-TrueNavPro,
                    Sierra-TrueNorth, Sierra-TrueSpeed, sitl, SITL_arm_linux_gnueabihf, sitl_periph_gps, SITL_static, SITL_x86_64_linux_gnu, SIYI_N7, SkystarsH7HD,
                    SkystarsH7HD-bdshot, skyviper-f412-rev1, skyviper-journey, skyviper-v2450, sparky2, speedybeef4, SpeedyBeeF405Mini, SpeedyBeeF405WING,
                    speedybeef4v3, speedybeef4v4, SPRacingH7, SPRacingH7RF, SuccexF4, sw-nav-f405, sw-spar-f407, Swan-K1, TBS-Colibri-F7, thepeach-k1, thepeach-r1,
                    TMotorH743, vnav, VRBrain-v51, VRBrain-v52, VRBrain-v54, VRCore-v10, VRUBrain-v51, YJUAV_A6, YJUAV_A6SE, YJUAV_A6SE_H743, ZubaxGNSS, zynq.
--debug             Configure as debug variant.
-g, --debug-symbols
                    Add debug symbolds to build.
--disable-watchdog  Build with watchdog disabled.
--coverage          Configure coverage flags.
--Werror            build with -Werror.
--disable-Werror    Disable -Werror.
--toolchain=TOOLCHAIN
                    Override default toolchain used for the board. Use "native" for using the host toolchain.
--disable-gccdeps   Disable the use of GCC dependencies output method and use waf default method.
--enable-asserts    enable OS level asserts.
--save-temps        save compiler temporary files.
--enable-malloc-guard
                    enable malloc guard regions.
--enable-stats      enable OS level thread statistics.
--bootloader        Configure for building a bootloader.
--signed-fw         Configure for signed firmware support.
--private-key=PRIVATE_KEY
                    path to private key for signing firmware.
--no-autoconfig     Disable autoconfiguration feature. By default, the build system triggers a reconfiguration whenever it thinks it's necessary - this option
                    disables that.
--no-submodule-update
                    Don't update git submodules. Useful for building with submodules at specific revisions.
--enable-header-checks
                    Enable checking of headers
--default-parameters=DEFAULT_PARAMETERS
                    set default parameters to embed in the firmware
--enable-math-check-indexes
                    Enable checking of math indexes
--disable-scripting
                    Disable onboard scripting engine
--enable-scripting  Enable onboard scripting engine
--no-gcs            Disable GCS code
--scripting-checks  Enable runtime scripting sanity checks
--enable-onvif      Enables and sets up ONVIF camera control
--scripting-docs    enable generation of scripting documentation
--enable-opendroneid
                    Enables OpenDroneID
--enable-check-firmware
                    Enables firmware ID checking on boot
--enable-custom-controller
                    Enables custom controller
--enable-gps-logging
                    Enables GPS logging
--enable-dds        Enable the dds client to connect with ROS2/DDS.
--disable-networking
                    Disable the networking API code
--enable-networking-tests
                    Enable the networking test code. Automatically enables networking.
--enable-dronecan-tests
                    Enables DroneCAN tests in sitl

4.3.3 Linux boards configure options

--prefix=PREFIX     installation prefix [default: '/usr/']
--destdir=DESTDIR   installation root [default: '']
--bindir=BINDIR     bindir
--libdir=LIBDIR     libdir
--apstatedir=APSTATEDIR
                    Where to save data like parameters, log and terrain. This is the --localstatedir + ArduPilots subdirectory [default: board-dependent, usually
                    /var/lib/ardupilot]
--rsync-dest=RSYNC_DEST
                    Destination for the rsync Waf command. It can be passed during configuration in order to save typing.
--enable-benchmarks
                    Enable benchmarks.
--enable-lttng      Enable lttng integration
--disable-libiio    Don't use libiio even if supported by board and dependencies available
--disable-tests     Disable compilation and test execution
--enable-sfml       Enable SFML graphics library
--enable-sfml-joystick
                    Enable SFML joystick input library
--enable-sfml-audio
                    Enable SFML audio library
--osd               Enable OSD support
--osd-fonts         Enable OSD support with fonts
--sitl-osd          Enable SITL OSD
--sitl-rgbled       Enable SITL RGBLed
--force-32bit       Force 32bit build
--build-dates       Include build date in binaries.  Appears in AUTOPILOT_VERSION.os_sw_version
--sitl-flash-storage
                    Use flash storage emulation.
--enable-ekf2       Configure with EKF2.
--disable-ekf3      Configure without EKF3.
--ekf-double        Configure EKF as double precision.
--ekf-single        Configure EKF as single precision.
--static            Force a static build
--postype-single    force single precision postype_t
--consistent-builds
                    force consistent build outputs for things like __LINE__
--extra-hwdef=EXTRA_HWDEF
                    Extra hwdef.dat file for custom build.
--assert-cc-version=ASSERT_CC_VERSION
                    fail configure if not using the specified gcc version
--num-aux-imus=NUM_AUX_IMUS
                    number of auxiliary IMUs
--board-start-time=BOARD_START_TIME
                    zero time on boot in microseconds

4.3.4 Ardupilot build options

--program-group=PROGRAM_GROUP
                    Select all programs that go in <PROGRAM_GROUP>/ for the build. Example: `waf --program-group examples` builds all examples. The special group
                    "all" selects all programs.
--upload            Upload applicable targets to a connected device. Not all platforms may support this. Example: `waf copter --upload` means "build arducopter and
                    upload it to my board".
--upload-port=UPLOAD_PORT
                    Specify the port to be used with the --upload option. For example a port of /dev/ttyS10 indicates that serial port 10 shuld be used.
--upload-force      Override board type check and continue loading. Same as using uploader.py --force.
--summary-all       Print build summary for all targets. By default, only information about the first 20 targets will be printed.

4.3.5 Ardupilot check options

--check-verbose     Output all test programs.
--define=DEFINE     Add C++ define to build.

4.3.6 Ardupilot clean options

--clean-all-sigs    Clean signatures for all tasks. By default, tasks that scan for implicit dependencies (like the compilation tasks) keep the dependency
                    information across clean commands, so that that information is changed only when really necessary. Also, some tasks that don't really produce
                    files persist their signature. This option avoids that behavior when cleaning the build.
--asan              Build using the macOS clang Address Sanitizer. In order to run with Address Sanitizer support llvm-symbolizer is required to be on the PATH.
                    This option is only supported on macOS versions of clang.
--ubsan             Build using the gcc undefined behaviour sanitizer
--ubsan-abort       Build using the gcc undefined behaviour sanitizer and abort on error

4.4 脚本分析

注:本次目的主要在于ChibiOS系统。

重要脚本文件如下:

  • ./Tools/ardupilotwaf/ardupilotwaf.py
  • ./Tools/ardupilotwaf/chibios.py

重要类&函数如下:

  • [ardupilotwaf.py] build_command
  • [boards.py] class chibios
./waf
 └──> ./ardupilot/modules/waf-light
     ├──> <python hex version check> 
     │   ├──> [Python >= 2.6 is required to create the waf file]
     │   └──> return
     ├──> [find/add waflib dir]
     └──> ./wscript
         ├──> [add ./Tools/ardupilotwaf/]
         ├──> ./Tools/ardupilotwaf/ardupilotwaf.py
		 │   ├──> ./Tools/ardupilotwaf/ap_library.py
		 │   ├──> ./Tools/ardupilotwaf/static_linking.py
		 │   ├──> ./Tools/ardupilotwaf/gbenchmark.py
		 │   ├──> ./Tools/ardupilotwaf/gtest.py
		 │   ├──> ./Tools/ardupilotwaf/build_summary.py
		 │   ├──> ./Tools/ardupilotwaf/git_submodule.py
		 │   ├──> ./Tools/ardupilotwaf/mavgen.py
		 │   ├──> ./Tools/ardupilotwaf/dronecangen.py
         │   └──> ./Tools/ardupilotwaf/ap_persistent.py
         ├──> ./Tools/ardupilotwaf/boards.py
		 │   ├──> ./Tools/ardupilotwaf/toolchain.py
		 │   ├──> ./Tools/ardupilotwaf/cxx_checks.py
		 │   ├──> ./Tools/ardupilotwaf/esp32.py
         │   │   └──> ./Tools/ardupilotwaf/cmake.py
		 │   ├──> ./Tools/ardupilotwaf/chibios.py
         │   └──> ./Tools/ardupilotwaf/embed.py
         ├──> [Fix Python 2 compatibility issue with Python 3]
         ├──> [Override Build execute and Configure post_recurse methods for autoconfigure purposes]
         ├──> ardupilotwaf.build_command('check',
         ├──> ardupilotwaf.build_command('check-all',
         ├──> ardupilotwaf.build_command('antennatracker', 'copter', 'heli', 'plane', 'rover', 'sub', 'blimp', 'bootloader','iofirmware','AP_Periph','replay',
         └──> ardupilotwaf.build_command('all', 'bin', 'tool', 'examples', 'tests', 'benchmarks',

5. wscript脚本

目标板配置、编译命令:

$ ./waf configure --board Aocoda-RC-H743Dual
$ ./waf plane

5.1 configure命令

wscript脚本中调用boards.py中的配置函数configure,最终通过chibios.py中的配置函数configure对目标板进行配置。

def configure(cfg):
	# we need to enable debug mode when building for gconv, and force it to sitl
    if cfg.options.board is None:
        cfg.options.board = 'sitl'

    boards_names = boards.get_boards_names()
    if not cfg.options.board in boards_names:
        for b in boards_names:
            if b.upper() == cfg.options.board.upper():
                cfg.options.board = b
                break
        
    cfg.env.BOARD = cfg.options.board
    cfg.env.DEBUG = cfg.options.debug
    cfg.env.DEBUG_SYMBOLS = cfg.options.debug_symbols
    cfg.env.COVERAGE = cfg.options.coverage
    cfg.env.AUTOCONFIG = cfg.options.autoconfig

    _set_build_context_variant(cfg.env.BOARD)
    cfg.setenv(cfg.env.BOARD)

    if cfg.options.signed_fw:
        cfg.env.AP_SIGNED_FIRMWARE = True
        cfg.options.enable_check_firmware = True

    cfg.env.BOARD = cfg.options.board
    cfg.env.DEBUG = cfg.options.debug
    cfg.env.DEBUG_SYMBOLS = cfg.options.debug_symbols
    cfg.env.COVERAGE = cfg.options.coverage
    cfg.env.FORCE32BIT = cfg.options.force_32bit
    cfg.env.ENABLE_ASSERTS = cfg.options.enable_asserts
    cfg.env.BOOTLOADER = cfg.options.bootloader
    cfg.env.ENABLE_MALLOC_GUARD = cfg.options.enable_malloc_guard
    cfg.env.ENABLE_STATS = cfg.options.enable_stats
    cfg.env.SAVE_TEMPS = cfg.options.save_temps

    cfg.env.HWDEF_EXTRA = cfg.options.extra_hwdef
    if cfg.env.HWDEF_EXTRA:
        cfg.env.HWDEF_EXTRA = os.path.abspath(cfg.env.HWDEF_EXTRA)

    cfg.env.OPTIONS = cfg.options.__dict__

    # Allow to differentiate our build from the make build
    cfg.define('WAF_BUILD', 1)

    cfg.msg('Autoconfiguration', 'enabled' if cfg.options.autoconfig else 'disabled')

    if cfg.options.static:
        cfg.msg('Using static linking', 'yes', color='YELLOW')
        cfg.env.STATIC_LINKING = True

    if cfg.options.num_aux_imus > 0:
        cfg.define('INS_AUX_INSTANCES', cfg.options.num_aux_imus)

    if cfg.options.board_start_time != 0:
        cfg.define('AP_BOARD_START_TIME', cfg.options.board_start_time)
        # also in env for hrt.c
        cfg.env.AP_BOARD_START_TIME = cfg.options.board_start_time

    # require python 3.8.x or later
    cfg.load('python')
    cfg.check_python_version(minver=(3,6,9))

    cfg.load('ap_library')

    cfg.msg('Setting board to', cfg.options.board)
    cfg.get_board().configure(cfg)

    cfg.load('clang_compilation_database')
    cfg.load('waf_unit_test')
    cfg.load('mavgen')
    cfg.load('dronecangen')

    cfg.env.SUBMODULE_UPDATE = cfg.options.submodule_update

    cfg.start_msg('Source is git repository')
    if cfg.srcnode.find_node('.git'):
        cfg.end_msg('yes')
    else:
        cfg.end_msg('no')
        cfg.env.SUBMODULE_UPDATE = False

    cfg.msg('Update submodules', 'yes' if cfg.env.SUBMODULE_UPDATE else 'no')
    cfg.load('git_submodule')

    if cfg.options.enable_benchmarks:
        cfg.load('gbenchmark')
    cfg.load('gtest')
    cfg.load('static_linking')
    cfg.load('build_summary')

    cfg.start_msg('Benchmarks')
    if cfg.env.HAS_GBENCHMARK:
        cfg.end_msg('enabled')
    else:
        cfg.end_msg('disabled', color='YELLOW')

    cfg.start_msg('Unit tests')
    if cfg.env.HAS_GTEST:
        cfg.end_msg('enabled')
    else:
        cfg.end_msg('disabled', color='YELLOW')

    cfg.start_msg('Scripting')
    if cfg.options.disable_scripting:
        cfg.end_msg('disabled', color='YELLOW')
    elif cfg.options.enable_scripting:
        cfg.end_msg('enabled')
    else:
        cfg.end_msg('maybe')
    cfg.recurse('libraries/AP_Scripting')

    cfg.recurse('libraries/AP_GPS')
    cfg.recurse('libraries/AP_HAL_SITL')
    cfg.recurse('libraries/SITL')

    cfg.start_msg('Scripting runtime checks')
    if cfg.options.scripting_checks:
        cfg.end_msg('enabled')
    else:
        cfg.end_msg('disabled', color='YELLOW')

    cfg.start_msg('Debug build')
    if cfg.env.DEBUG:
        cfg.end_msg('enabled')
    else:
        cfg.end_msg('disabled', color='YELLOW')

    cfg.start_msg('Coverage build')
    if cfg.env.COVERAGE:
        cfg.end_msg('enabled')
    else:
        cfg.end_msg('disabled', color='YELLOW')

    cfg.start_msg('Force 32-bit build')
    if cfg.env.FORCE32BIT:
        cfg.end_msg('enabled')
    else:
        cfg.end_msg('disabled', color='YELLOW')

    cfg.env.append_value('GIT_SUBMODULES', 'mavlink')

    cfg.env.prepend_value('INCLUDES', [
        cfg.srcnode.abspath() + '/libraries/',
    ])

    cfg.find_program('rsync', mandatory=False)
    if cfg.options.rsync_dest:
        cfg.msg('Setting rsync destination to', cfg.options.rsync_dest)
        cfg.env.RSYNC_DEST = cfg.options.rsync_dest

    if cfg.options.enable_header_checks:
        cfg.msg('Enabling header checks', cfg.options.enable_header_checks)
        cfg.env.ENABLE_HEADER_CHECKS = True
    else:
        cfg.env.ENABLE_HEADER_CHECKS = False

    # Always use system extensions
    cfg.define('_GNU_SOURCE', 1)

    if cfg.options.Werror:
        # print(cfg.options.Werror)
        if cfg.options.disable_Werror:
            cfg.options.Werror = False

    cfg.write_config_header(os.path.join(cfg.variant, 'ap_config.h'), guard='_AP_CONFIG_H_')

    # add in generated flags
    cfg.env.CXXFLAGS += ['-include', 'ap_config.h']

    _collect_autoconfig_files(cfg)

def configure(cfg):
    cfg.find_program('make', var='MAKE')
    #cfg.objcopy = cfg.find_program('%s-%s'%(cfg.env.TOOLCHAIN,'objcopy'), var='OBJCOPY', mandatory=True)
    cfg.find_program('arm-none-eabi-objcopy', var='OBJCOPY')
    env = cfg.env
    bldnode = cfg.bldnode.make_node(cfg.variant)
    def srcpath(path):
        return cfg.srcnode.make_node(path).abspath()

    def bldpath(path):
        return bldnode.make_node(path).abspath()
    env.AP_PROGRAM_FEATURES += ['ch_ap_program']

    kw = env.AP_LIBRARIES_OBJECTS_KW
    kw['features'] = Utils.to_list(kw.get('features', [])) + ['ch_ap_library']

    env.CH_ROOT = srcpath('modules/ChibiOS')
    env.CC_ROOT = srcpath('modules/CrashDebug/CrashCatcher')
    env.AP_HAL_ROOT = srcpath('libraries/AP_HAL_ChibiOS')
    env.BUILDDIR = bldpath('modules/ChibiOS')
    env.BUILDROOT = bldpath('')
    env.SRCROOT = srcpath('')
    env.PT_DIR = srcpath('Tools/ardupilotwaf/chibios/image')
    env.MKFW_TOOLS = srcpath('Tools/ardupilotwaf')
    env.UPLOAD_TOOLS = srcpath('Tools/scripts')
    env.CHIBIOS_SCRIPTS = srcpath('libraries/AP_HAL_ChibiOS/hwdef/scripts')
    env.TOOLS_SCRIPTS = srcpath('Tools/scripts')
    env.APJ_TOOL = srcpath('Tools/scripts/apj_tool.py')
    env.SERIAL_PORT = srcpath('/dev/serial/by-id/*_STLink*')

    # relative paths to pass to make, relative to directory that make is run from
    env.CH_ROOT_REL = os.path.relpath(env.CH_ROOT, env.BUILDROOT)
    env.CC_ROOT_REL = os.path.relpath(env.CC_ROOT, env.BUILDROOT)
    env.AP_HAL_REL = os.path.relpath(env.AP_HAL_ROOT, env.BUILDROOT)
    env.BUILDDIR_REL = os.path.relpath(env.BUILDDIR, env.BUILDROOT)

    mk_custom = srcpath('libraries/AP_HAL_ChibiOS/hwdef/%s/chibios_board.mk' % env.BOARD)
    mk_common = srcpath('libraries/AP_HAL_ChibiOS/hwdef/common/chibios_board.mk')
    # see if there is a board specific make file
    if os.path.exists(mk_custom):
        env.BOARD_MK = mk_custom
    else:
        env.BOARD_MK = mk_common

    if cfg.options.default_parameters:
        cfg.msg('Default parameters', cfg.options.default_parameters, color='YELLOW')
        env.DEFAULT_PARAMETERS = cfg.options.default_parameters

    try:
        ret = generate_hwdef_h(env)
    except Exception:
        cfg.fatal("Failed to process hwdef.dat")
    if ret != 0:
        cfg.fatal("Failed to process hwdef.dat ret=%d" % ret)
    load_env_vars(cfg.env)
    if env.HAL_NUM_CAN_IFACES and not env.AP_PERIPH:
        setup_canmgr_build(cfg)
    if env.HAL_NUM_CAN_IFACES and env.AP_PERIPH and not env.BOOTLOADER:
        setup_canperiph_build(cfg)
    if env.HAL_NUM_CAN_IFACES and env.AP_PERIPH and int(env.HAL_NUM_CAN_IFACES)>1 and not env.BOOTLOADER:
        env.DEFINES += [ 'CANARD_MULTI_IFACE=1' ]
    setup_optimization(cfg.env)

5.2 plane命令

wscript脚本中调用build_command生成动态target plane,最终通过chibios.py中的配置函数build对代码进行二进制构建。

def build_command(name,
                   targets=None,
                   program_group_list=[],
                   doc='build shortcut'):
    _build_commands[name] = dict(
        targets=targets,
        program_group_list=program_group_list,
    )

    class context_class(Build.BuildContext):
        cmd = name
    context_class.__doc__ = doc


def build(bld):


    hwdef_rule="%s '%s/hwdef/scripts/chibios_hwdef.py' -D '%s' --params '%s' '%s'" % (
            bld.env.get_flat('PYTHON'),
            bld.env.AP_HAL_ROOT,
            bld.env.BUILDROOT,
            bld.env.default_parameters,
            bld.env.HWDEF)
    if bld.env.HWDEF_EXTRA:
        hwdef_rule += " " + bld.env.HWDEF_EXTRA
    if bld.env.BOOTLOADER_OPTION:
        hwdef_rule += " " + bld.env.BOOTLOADER_OPTION
    bld(
        # build hwdef.h from hwdef.dat. This is needed after a waf clean
        source=bld.path.ant_glob(bld.env.HWDEF),
        rule=hwdef_rule,
        group='dynamic_sources',
        target=[bld.bldnode.find_or_declare('hwdef.h'),
                bld.bldnode.find_or_declare('ldscript.ld'),
                bld.bldnode.find_or_declare('hw.dat')]
    )
    
    bld(
        # create the file modules/ChibiOS/include_dirs
        rule="touch Makefile && BUILDDIR=${BUILDDIR_REL} BUILDROOT=${BUILDROOT} CRASHCATCHER=${CC_ROOT_REL} CHIBIOS=${CH_ROOT_REL} AP_HAL=${AP_HAL_REL} ${CHIBIOS_BUILD_FLAGS} ${CHIBIOS_BOARD_NAME} ${MAKE} pass -f '${BOARD_MK}'",
        group='dynamic_sources',
        target=bld.bldnode.find_or_declare('modules/ChibiOS/include_dirs')
    )

    bld(
        # create the file modules/ChibiOS/include_dirs
        rule="echo // BUILD_FLAGS: ${BUILDDIR_REL} ${BUILDROOT} ${CC_ROOT_REL} ${CH_ROOT_REL} ${AP_HAL_REL} ${CHIBIOS_BUILD_FLAGS} ${CHIBIOS_BOARD_NAME} ${HAL_MAX_STACK_FRAME_SIZE} > chibios_flags.h",
        group='dynamic_sources',
        target=bld.bldnode.find_or_declare('chibios_flags.h')
    )
    
    common_src = [bld.bldnode.find_or_declare('hwdef.h'),
                  bld.bldnode.find_or_declare('hw.dat'),
                  bld.bldnode.find_or_declare('ldscript.ld'),
                  bld.bldnode.find_or_declare('common.ld'),
                  bld.bldnode.find_or_declare('modules/ChibiOS/include_dirs')]
    common_src += bld.path.ant_glob('libraries/AP_HAL_ChibiOS/hwdef/common/*.[ch]')
    common_src += bld.path.ant_glob('libraries/AP_HAL_ChibiOS/hwdef/common/*.mk')
    common_src += bld.path.ant_glob('modules/ChibiOS/os/hal/**/*.[ch]')
    common_src += bld.path.ant_glob('modules/ChibiOS/os/hal/**/*.mk')
    common_src += bld.path.ant_glob('modules/ChibiOS/ext/lwip/src/**/*.[ch]')
    common_src += bld.path.ant_glob('modules/ChibiOS/ext/lwip/src/core/**/*.[ch]')
    if bld.env.ROMFS_FILES:
        common_src += [bld.bldnode.find_or_declare('ap_romfs_embedded.h')]

    if bld.env.ENABLE_CRASHDUMP:
        ch_task = bld(
            # build libch.a from ChibiOS sources and hwdef.h
            rule="BUILDDIR='${BUILDDIR_REL}' BUILDROOT='${BUILDROOT}' CRASHCATCHER='${CC_ROOT_REL}' CHIBIOS='${CH_ROOT_REL}' AP_HAL=${AP_HAL_REL} ${CHIBIOS_BUILD_FLAGS} ${CHIBIOS_BOARD_NAME} ${HAL_MAX_STACK_FRAME_SIZE} '${MAKE}' -j%u lib -f '${BOARD_MK}'" % bld.options.jobs,
            group='dynamic_sources',
            source=common_src,
            target=[bld.bldnode.find_or_declare('modules/ChibiOS/libch.a'), bld.bldnode.find_or_declare('modules/ChibiOS/libcc.a')]
        )
    else:
        ch_task = bld(
            # build libch.a from ChibiOS sources and hwdef.h
            rule="BUILDDIR='${BUILDDIR_REL}' BUILDROOT='${BUILDROOT}' CHIBIOS='${CH_ROOT_REL}' AP_HAL=${AP_HAL_REL} ${CHIBIOS_BUILD_FLAGS} ${CHIBIOS_BOARD_NAME} ${HAL_MAX_STACK_FRAME_SIZE} '${MAKE}' -j%u lib -f '${BOARD_MK}'" % bld.options.jobs,
            group='dynamic_sources',
            source=common_src,
            target=bld.bldnode.find_or_declare('modules/ChibiOS/libch.a')
        )
    ch_task.name = "ChibiOS_lib"
    DSP_LIBS = {
        'cortex-m4' : 'libarm_cortexM4lf_math.a',
        'cortex-m7' : 'libarm_cortexM7lfdp_math.a',
    }
    if bld.env.CORTEX in DSP_LIBS:
        libname = DSP_LIBS[bld.env.CORTEX]
        # we need to copy the library on cygwin as it doesn't handle linking outside build tree
        shutil.copyfile(os.path.join(bld.env.SRCROOT,'libraries/AP_GyroFFT/CMSIS_5/lib',libname),
                        os.path.join(bld.env.BUILDROOT,'modules/ChibiOS/libDSP.a'))
        bld.env.LIB += ['DSP']
    bld.env.LIB += ['ch']
    bld.env.LIBPATH += ['modules/ChibiOS/']
    if bld.env.ENABLE_CRASHDUMP:
        bld.env.LINKFLAGS += ['-Wl,-whole-archive', 'modules/ChibiOS/libcc.a', '-Wl,-no-whole-archive']
    # list of functions that will be wrapped to move them out of libc into our
    # own code note that we also include functions that we deliberately don't
    # implement anywhere (the FILE* functions). This allows us to get link
    # errors if we accidentially try to use one of those functions either
    # directly or via another libc call
    wraplist = ['sscanf', 'fprintf', 'snprintf', 'vsnprintf','vasprintf','asprintf','vprintf','scanf',
                'fiprintf','printf',
                'fopen', 'fflush', 'fwrite', 'fread', 'fputs', 'fgets',
                'clearerr', 'fseek', 'ferror', 'fclose', 'tmpfile', 'getc', 'ungetc', 'feof',
                'ftell', 'freopen', 'remove', 'vfprintf', 'fscanf',
                '_gettimeofday', '_times', '_times_r', '_gettimeofday_r', 'time', 'clock',
                '_sbrk', '_sbrk_r', '_malloc_r', '_calloc_r', '_free_r']
    for w in wraplist:

6. 总结

通过上面waf和``wscript`脚本的分析,可以归纳出:

  1. waf提供了一个命令行集成开发环境;
  2. 支持目标板选择;
  3. 支持微系统选择;
  4. 支持编译配置选择;
  5. 支持目标板固件烧;
  6. 支持CI功能:比如:单元测试,覆盖率测试等

7. 参考资料

【1】ArduPilot开源飞控系统之简单介绍
【2】ArduPilot之开源代码框架
【3】Ardupilot开源飞控之ChibiOS简介

文章来源:https://blog.csdn.net/lida2003/article/details/135167962
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。