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 wscript代码

#!/usr/bin/env python3
# encoding: utf-8

from __future__ import print_function

import os.path
import os
import sys
import subprocess
import json
import fnmatch
sys.path.insert(0, 'Tools/ardupilotwaf/')

import ardupilotwaf
import boards
import shutil

from waflib import Build, ConfigSet, Configure, Context, Utils
from waflib.Configure import conf

# Ref: https://stackoverflow.com/questions/40590192/getting-an-error-attributeerror-module-object-has-no-attribute-run-while
try:
    from subprocess import CompletedProcess
except ImportError:
    # Python 2
    class CompletedProcess:

        def __init__(self, args, returncode, stdout=None, stderr=None):
            self.args = args
            self.returncode = returncode
            self.stdout = stdout
            self.stderr = stderr

        def check_returncode(self):
            if self.returncode != 0:
                err = subprocess.CalledProcessError(self.returncode, self.args, output=self.stdout)
                raise err
            return self.returncode

    def sp_run(*popenargs, **kwargs):
        input = kwargs.pop("input", None)
        check = kwargs.pop("handle", False)
        kwargs.pop("capture_output", True)
        if input is not None:
            if 'stdin' in kwargs:
                raise ValueError('stdin and input arguments may not both be used.')
            kwargs['stdin'] = subprocess.PIPE
        process = subprocess.Popen(*popenargs, **kwargs)
        try:
            outs, errs = process.communicate(input)
        except:
            process.kill()
            process.wait()
            raise
        returncode = process.poll()
        if check and returncode:
            raise subprocess.CalledProcessError(returncode, popenargs, output=outs)
        return CompletedProcess(popenargs, returncode, stdout=outs, stderr=errs)

    subprocess.run = sp_run
    # ^ This monkey patch allows it work on Python 2 or 3 the same way


# TODO: implement a command 'waf help' that shows the basic tasks a
# developer might want to do: e.g. how to configure a board, compile a
# vehicle, compile all the examples, add a new example. Should fit in
# less than a terminal screen, ideally commands should be copy
# pastable. Add the 'export waf="$PWD/waf"' trick to be copy-pastable
# as well.

# TODO: replace defines with the use of the generated ap_config.h file
# this makes recompilation at least when defines change. which might
# be sufficient.

# Default installation prefix for Linux boards
default_prefix = '/usr/'

# Override Build execute and Configure post_recurse methods for autoconfigure purposes
Build.BuildContext.execute = ardupilotwaf.ap_autoconfigure(Build.BuildContext.execute)
Configure.ConfigurationContext.post_recurse = ardupilotwaf.ap_configure_post_recurse()


def _set_build_context_variant(board):
    for c in Context.classes:
        if not issubclass(c, Build.BuildContext):
            continue
        c.variant = board

def init(ctx):
    # Generate Task List, so that VS Code extension can keep track
    # of changes to possible build targets
    generate_tasklist(ctx, False)
    env = ConfigSet.ConfigSet()
    try:
        p = os.path.join(Context.out_dir, Build.CACHE_DIR, Build.CACHE_SUFFIX)
        env.load(p)
    except EnvironmentError:
        return

    Configure.autoconfig = 'clobber' if env.AUTOCONFIG else False

    board = ctx.options.board or env.BOARD

    if not board:
        return

    # define the variant build commands according to the board
    _set_build_context_variant(board)

def options(opt):
    opt.load('compiler_cxx compiler_c waf_unit_test python')
    opt.load('ardupilotwaf')
    opt.load('build_summary')

    g = opt.ap_groups['configure']

    boards_names = boards.get_boards_names()
    removed_names = boards.get_removed_boards()
    g.add_option('--board',
        action='store',
        default=None,
        help='Target board to build, choices are %s.' % ', '.join(boards_names))

    g.add_option('--debug',
        action='store_true',
        default=False,
        help='Configure as debug variant.')

    g.add_option('--debug-symbols', '-g',
        action='store_true',
        default=False,
        help='Add debug symbolds to build.')
    
    g.add_option('--disable-watchdog',
        action='store_true',
        default=False,
        help='Build with watchdog disabled.')

    g.add_option('--coverage',
                 action='store_true',
                 default=False,
                 help='Configure coverage flags.')

    g.add_option('--Werror',
        action='store_true',
        default=None,
        help='build with -Werror.')

    g.add_option('--disable-Werror',
        action='store_true',
        default=None,
        help='Disable -Werror.')
    
    g.add_option('--toolchain',
        action='store',
        default=None,
        help='Override default toolchain used for the board. Use "native" for using the host toolchain.')

    g.add_option('--disable-gccdeps',
        action='store_true',
        default=False,
        help='Disable the use of GCC dependencies output method and use waf default method.')

    g.add_option('--enable-asserts',
        action='store_true',
        default=False,
        help='enable OS level asserts.')

    g.add_option('--save-temps',
        action='store_true',
        default=False,
        help='save compiler temporary files.')
    
    g.add_option('--enable-malloc-guard',
        action='store_true',
        default=False,
        help='enable malloc guard regions.')

    g.add_option('--enable-stats',
        action='store_true',
        default=False,
        help='enable OS level thread statistics.')
    
    g.add_option('--bootloader',
        action='store_true',
        default=False,
        help='Configure for building a bootloader.')

    g.add_option('--signed-fw',
        action='store_true',
        default=False,
        help='Configure for signed firmware support.')

    g.add_option('--private-key',
                 action='store',
                 default=None,
            help='path to private key for signing firmware.')
    
    g.add_option('--no-autoconfig',
        dest='autoconfig',
        action='store_false',
        default=True,
        help='''Disable autoconfiguration feature. By default, the build system
triggers a reconfiguration whenever it thinks it's necessary - this
option disables that.
''')

    g.add_option('--no-submodule-update',
        dest='submodule_update',
        action='store_false',
        default=True,
        help='''Don't update git submodules. Useful for building with
submodules at specific revisions.
''')

    g.add_option('--enable-header-checks', action='store_true',
        default=False,
        help="Enable checking of headers")

    g.add_option('--default-parameters',
        default=None,
        help='set default parameters to embed in the firmware')

    g.add_option('--enable-math-check-indexes',
                 action='store_true',
                 default=False,
                 help="Enable checking of math indexes")

    g.add_option('--disable-scripting', action='store_true',
                 default=False,
                 help="Disable onboard scripting engine")

    g.add_option('--enable-scripting', action='store_true',
                 default=False,
                 help="Enable onboard scripting engine")

    g.add_option('--no-gcs', action='store_true',
                 default=False,
                 help="Disable GCS code")
    
    g.add_option('--scripting-checks', action='store_true',
                 default=True,
                 help="Enable runtime scripting sanity checks")

    g.add_option('--enable-onvif', action='store_true',
                 default=False,
                 help="Enables and sets up ONVIF camera control")

    g.add_option('--scripting-docs', action='store_true',
                 default=False,
                 help="enable generation of scripting documentation")

    g.add_option('--enable-opendroneid', action='store_true',
                 default=False,
                 help="Enables OpenDroneID")

    g.add_option('--enable-check-firmware', action='store_true',
                 default=False,
                 help="Enables firmware ID checking on boot")

    g.add_option('--enable-custom-controller', action='store_true',
                 default=False,
                 help="Enables custom controller")

    g.add_option('--enable-gps-logging', action='store_true',
                 default=False,
                 help="Enables GPS logging")
    
    g.add_option('--enable-dds', action='store_true',
                 help="Enable the dds client to connect with ROS2/DDS.")

    g.add_option('--disable-networking', action='store_true',
                 help="Disable the networking API code")

    g.add_option('--enable-networking-tests', action='store_true',
                 help="Enable the networking test code. Automatically enables networking.")
    
    g.add_option('--enable-dronecan-tests', action='store_true',
                 default=False,
                 help="Enables DroneCAN tests in sitl")
    g = opt.ap_groups['linux']

    linux_options = ('--prefix', '--destdir', '--bindir', '--libdir')
    for k in linux_options:
        option = opt.parser.get_option(k)
        if option:
            opt.parser.remove_option(k)
            g.add_option(option)

    g.add_option('--apstatedir',
        action='store',
        default='',
        help='''Where to save data like parameters, log and terrain.
This is the --localstatedir + ArduPilots subdirectory [default:
board-dependent, usually /var/lib/ardupilot]''')

    g.add_option('--rsync-dest',
        dest='rsync_dest',
        action='store',
        default='',
        help='''Destination for the rsync Waf command. It can be passed during
configuration in order to save typing.
''')

    g.add_option('--enable-benchmarks',
        action='store_true',
        default=False,
        help='Enable benchmarks.')

    g.add_option('--enable-lttng', action='store_true',
        default=False,
        help="Enable lttng integration")

    g.add_option('--disable-libiio', action='store_true',
        default=False,
        help="Don't use libiio even if supported by board and dependencies available")

    g.add_option('--disable-tests', action='store_true',
        default=False,
        help="Disable compilation and test execution")

    g.add_option('--enable-sfml', action='store_true',
                 default=False,
                 help="Enable SFML graphics library")

    g.add_option('--enable-sfml-joystick', action='store_true',
                 default=False,
                 help="Enable SFML joystick input library")

    g.add_option('--enable-sfml-audio', action='store_true',
                 default=False,
                 help="Enable SFML audio library")

    g.add_option('--osd', action='store_true',
                 default=False,
                 help="Enable OSD support")

    g.add_option('--osd-fonts', action='store_true',
                 default=False,
                 help="Enable OSD support with fonts")
    
    g.add_option('--sitl-osd', action='store_true',
                 default=False,
                 help="Enable SITL OSD")

    g.add_option('--sitl-rgbled', action='store_true',
                 default=False,
                 help="Enable SITL RGBLed")

    g.add_option('--force-32bit', action='store_true',
                 default=False,
                 help="Force 32bit build")

    g.add_option('--build-dates', action='store_true',
                 default=False,
                 help="Include build date in binaries.  Appears in AUTOPILOT_VERSION.os_sw_version")

    g.add_option('--sitl-flash-storage',
        action='store_true',
        default=False,
        help='Use flash storage emulation.')

    g.add_option('--enable-ekf2',
        action='store_true',
        default=False,
        help='Configure with EKF2.')

    g.add_option('--disable-ekf3',
        action='store_true',
        default=False,
        help='Configure without EKF3.')

    g.add_option('--ekf-double',
        action='store_true',
        default=False,
        help='Configure EKF as double precision.')

    g.add_option('--ekf-single',
        action='store_true',
        default=False,
        help='Configure EKF as single precision.')
    
    g.add_option('--static',
        action='store_true',
        default=False,
        help='Force a static build')

    g.add_option('--postype-single',
        action='store_true',
        default=False,
        help='force single precision postype_t')

    g.add_option('--consistent-builds',
        action='store_true',
        default=False,
        help='force consistent build outputs for things like __LINE__')

    g.add_option('--extra-hwdef',
	    action='store',
	    default=None,
	    help='Extra hwdef.dat file for custom build.')

    g.add_option('--assert-cc-version',
                 default=None,
                 help='fail configure if not using the specified gcc version')

    g.add_option('--num-aux-imus',
                 type='int',
                 default=0,
                 help='number of auxiliary IMUs')

    g.add_option('--board-start-time',
                 type='int',
                 default=0,
                 help='zero time on boot in microseconds')
    
def _collect_autoconfig_files(cfg):
    for m in sys.modules.values():
        paths = []
        if hasattr(m, '__file__') and m.__file__ is not None:
            paths.append(m.__file__)
        elif hasattr(m, '__path__'):
            for p in m.__path__:
                if p is not None:
                    paths.append(p)

        for p in paths:
            if p in cfg.files or not os.path.isfile(p):
                continue

            with open(p, 'rb') as f:
                cfg.hash = Utils.h_list((cfg.hash, f.read()))
                cfg.files.append(p)

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 collect_dirs_to_recurse(bld, globs, **kw):
    dirs = []
    globs = Utils.to_list(globs)

    if bld.bldnode.is_child_of(bld.srcnode):
        kw['excl'] = Utils.to_list(kw.get('excl', []))
        kw['excl'].append(bld.bldnode.path_from(bld.srcnode))

    for g in globs:
        for d in bld.srcnode.ant_glob(g + '/wscript', **kw):
            dirs.append(d.parent.relpath())
    return dirs

def list_boards(ctx):
    print(*boards.get_boards_names())

def list_ap_periph_boards(ctx):
    print(*boards.get_ap_periph_boards())

@conf
def ap_periph_boards(ctx):
    return boards.get_ap_periph_boards()

def generate_tasklist(ctx, do_print=True):
    boardlist = boards.get_boards_names()
    ap_periph_targets = boards.get_ap_periph_boards()
    tasks = []
    with open(os.path.join(Context.top_dir, "tasklist.json"), "w") as tlist:
        for board in boardlist:
            task = {}
            task['configure'] = board
            if board in ap_periph_targets:
                if 'sitl' not in board:
                    # we only support AP_Periph and bootloader builds
                    task['targets'] = ['AP_Periph', 'bootloader']
                else:
                    task['targets'] = ['AP_Periph']
            elif 'iofirmware' in board:
                task['targets'] = ['iofirmware', 'bootloader']
            else:
                if 'sitl' in board or 'SITL' in board:
                    task['targets'] = ['antennatracker', 'copter', 'heli', 'plane', 'rover', 'sub', 'replay']
                elif 'linux' in board:
                    task['targets'] = ['antennatracker', 'copter', 'heli', 'plane', 'rover', 'sub']
                else:
                    task['targets'] = ['antennatracker', 'copter', 'heli', 'plane', 'rover', 'sub', 'bootloader']
                    task['buildOptions'] = '--upload'
            tasks.append(task)
        tlist.write(json.dumps(tasks))
        if do_print:
            print(json.dumps(tasks))

def board(ctx):
    env = ConfigSet.ConfigSet()
    try:
        p = os.path.join(Context.out_dir, Build.CACHE_DIR, Build.CACHE_SUFFIX)
        env.load(p)
    except:
        print('No board currently configured')
        return

    print('Board configured to: {}'.format(env.BOARD))

def _build_cmd_tweaks(bld):
    if bld.cmd == 'check-all':
        bld.options.all_tests = True
        bld.cmd = 'check'

    if bld.cmd == 'check':
        if not bld.env.HAS_GTEST:
            bld.fatal('check: gtest library is required')
        bld.options.clear_failed_tests = True

def _build_dynamic_sources(bld):
    if not bld.env.BOOTLOADER:
        bld(
            features='mavgen',
            source='modules/mavlink/message_definitions/v1.0/all.xml',
            output_dir='libraries/GCS_MAVLink/include/mavlink/v2.0/',
            name='mavlink',
            # this below is not ideal, mavgen tool should set this, but that's not
            # currently possible
            export_includes=[
            bld.bldnode.make_node('libraries').abspath(),
            bld.bldnode.make_node('libraries/GCS_MAVLink').abspath(),
            ],
            )

    if (bld.get_board().with_can or bld.env.HAL_NUM_CAN_IFACES) and not bld.env.AP_PERIPH:
        bld(
            features='dronecangen',
            source=bld.srcnode.ant_glob('modules/DroneCAN/DSDL/* libraries/AP_DroneCAN/dsdl/*', dir=True, src=False),
            output_dir='modules/DroneCAN/libcanard/dsdlc_generated/',
            name='dronecan',
            export_includes=[
                bld.bldnode.make_node('modules/DroneCAN/libcanard/dsdlc_generated/include').abspath(),
                bld.srcnode.find_dir('modules/DroneCAN/libcanard/').abspath(),
                bld.srcnode.find_dir('libraries/AP_DroneCAN/canard/').abspath(),
                ]
            )
    elif bld.env.AP_PERIPH:
        bld(
            features='dronecangen',
            source=bld.srcnode.ant_glob('modules/DroneCAN/DSDL/* libraries/AP_DroneCAN/dsdl/*', dir=True, src=False),
            output_dir='modules/DroneCAN/libcanard/dsdlc_generated/',
            name='dronecan',
            export_includes=[
                bld.bldnode.make_node('modules/DroneCAN/libcanard/dsdlc_generated/include').abspath(),
                bld.srcnode.find_dir('modules/DroneCAN/libcanard/').abspath(),
            ]
        )

    if bld.env.ENABLE_DDS:
        bld.recurse("libraries/AP_DDS")

    def write_version_header(tsk):
        bld = tsk.generator.bld
        return bld.write_version_header(tsk.outputs[0].abspath())

    bld(
        name='ap_version',
        target='ap_version.h',
        vars=['AP_VERSION_ITEMS'],
        rule=write_version_header,
    )

    bld.env.prepend_value('INCLUDES', [
        bld.bldnode.abspath(),
    ])

def _build_common_taskgens(bld):
    # NOTE: Static library with vehicle set to UNKNOWN, shared by all
    # the tools and examples. This is the first step until the
    # dependency on the vehicles is reduced. Later we may consider
    # split into smaller pieces with well defined boundaries.
    bld.ap_stlib(
        name='ap',
        ap_vehicle='UNKNOWN',
        ap_libraries=bld.ap_get_all_libraries(),
    )

    if bld.env.HAS_GTEST:
        bld.libgtest(cxxflags=['-include', 'ap_config.h'])

    if bld.env.HAS_GBENCHMARK:
        bld.libbenchmark()

def _build_recursion(bld):
    common_dirs_patterns = [
        # TODO: Currently each vehicle also generate its own copy of the
        # libraries. Fix this, or at least reduce the amount of
        # vehicle-dependent libraries.
        '*',
        'Tools/*',
        'libraries/*/examples/*',
        'libraries/*/tests',
        'libraries/*/utility/tests',
        'libraries/*/benchmarks',
    ]

    common_dirs_excl = [
        'modules',
        'libraries/AP_HAL_*',
    ]

    hal_dirs_patterns = [
        'libraries/%s/tests',
        'libraries/%s/*/tests',
        'libraries/%s/*/benchmarks',
        'libraries/%s/examples/*',
    ]

    dirs_to_recurse = collect_dirs_to_recurse(
        bld,
        common_dirs_patterns,
        excl=common_dirs_excl,
    )
    if bld.env.IOMCU_FW is not None:
        if bld.env.IOMCU_FW:
            dirs_to_recurse.append('libraries/AP_IOMCU/iofirmware')

    if bld.env.PERIPH_FW is not None:
        if bld.env.PERIPH_FW:
            dirs_to_recurse.append('Tools/AP_Periph')

    dirs_to_recurse.append('libraries/AP_Scripting')

    if bld.env.ENABLE_ONVIF:
        dirs_to_recurse.append('libraries/AP_ONVIF')

    for p in hal_dirs_patterns:
        dirs_to_recurse += collect_dirs_to_recurse(
            bld,
            [p % l for l in bld.env.AP_LIBRARIES],
        )

    # NOTE: we need to sort to ensure the repeated sources get the
    # same index, and random ordering of the filesystem doesn't cause
    # recompilation.
    dirs_to_recurse.sort()

    for d in dirs_to_recurse:
        bld.recurse(d)

def _build_post_funs(bld):
    if bld.cmd == 'check':
        bld.add_post_fun(ardupilotwaf.test_summary)
    else:
        bld.build_summary_post_fun()

    if bld.env.SUBMODULE_UPDATE:
        bld.git_submodule_post_fun()

def _load_pre_build(bld):
    '''allow for a pre_build() function in build modules'''
    if bld.cmd == 'clean':
        return
    brd = bld.get_board()
    if getattr(brd, 'pre_build', None):
        brd.pre_build(bld)    

def build(bld):
    config_hash = Utils.h_file(bld.bldnode.make_node('ap_config.h').abspath())
    bld.env.CCDEPS = config_hash
    bld.env.CXXDEPS = config_hash

    bld.post_mode = Build.POST_LAZY

    bld.load('ardupilotwaf')

    bld.env.AP_LIBRARIES_OBJECTS_KW.update(
        use=['mavlink'],
        cxxflags=['-include', 'ap_config.h'],
    )

    _load_pre_build(bld)

    if bld.get_board().with_can:
        bld.env.AP_LIBRARIES_OBJECTS_KW['use'] += ['dronecan']

    _build_cmd_tweaks(bld)

    if bld.env.SUBMODULE_UPDATE:
        bld.add_group('git_submodules')
        for name in bld.env.GIT_SUBMODULES:
            bld.git_submodule(name)

    bld.add_group('dynamic_sources')
    _build_dynamic_sources(bld)

    bld.add_group('build')
    bld.get_board().build(bld)
    _build_common_taskgens(bld)

    _build_recursion(bld)

    _build_post_funs(bld)

ardupilotwaf.build_command('check',
    program_group_list='all',
    doc='builds all programs and run tests',
)
ardupilotwaf.build_command('check-all',
    program_group_list='all',
    doc='shortcut for `waf check --alltests`',
)

for name in ('antennatracker', 'copter', 'heli', 'plane', 'rover', 'sub', 'blimp', 'bootloader','iofirmware','AP_Periph','replay'):
    ardupilotwaf.build_command(name,
        program_group_list=name,
        doc='builds %s programs' % name,
    )

for program_group in ('all', 'bin', 'tool', 'examples', 'tests', 'benchmarks'):
    ardupilotwaf.build_command(program_group,
        program_group_list=program_group,
        doc='builds all programs of %s group' % program_group,
    )

class LocalInstallContext(Build.InstallContext):
    """runs install using BLD/install as destdir, where BLD is the build variant directory"""
    cmd = 'localinstall'

    def __init__(self, **kw):
        super(LocalInstallContext, self).__init__(**kw)
        self.local_destdir = os.path.join(self.variant_dir, 'install')

    def execute(self):
        old_destdir = self.options.destdir
        self.options.destdir = self.local_destdir
        r = super(LocalInstallContext, self).execute()
        self.options.destdir = old_destdir
        return r

class RsyncContext(LocalInstallContext):
    """runs localinstall and then rsyncs BLD/install with the target system"""
    cmd = 'rsync'

    def __init__(self, **kw):
        super(RsyncContext, self).__init__(**kw)
        self.add_pre_fun(RsyncContext.create_rsync_taskgen)

    def create_rsync_taskgen(self):
        if 'RSYNC' not in self.env:
            self.fatal('rsync program seems not to be installed, can\'t continue')

        self.add_group()

        tg = self(
            name='rsync',
            rule='${RSYNC} -a ${RSYNC_SRC}/ ${RSYNC_DEST}',
            always=True,
        )

        tg.env.RSYNC_SRC = self.local_destdir
        if self.options.rsync_dest:
            self.env.RSYNC_DEST = self.options.rsync_dest

        if 'RSYNC_DEST' not in tg.env:
            self.fatal('Destination for rsync not defined. Either pass --rsync-dest here or during configuration.')

        tg.post()

5.2 wscript功能

主要组件和功能概述:

  1. Imports and Setup:

Import necessary modules and libraries.
Set the default installation prefix for Linux boards.

  1. Monkey Patching:

Some modifications are made to the subprocess module to handle compatibility issues between Python 2 and 3.

  1. Configuration Options:

Define various configuration options and command-line arguments for the build process.
Options include the target board, debug mode, debug symbols, coverage, toolchain selection, etc.

  1. Customization of Build Context:

Override methods in the Waf build context to implement custom behavior related to autoconfiguration and variant build commands.

  1. Initialization and Configuration:

Set up the build environment based on configuration options.
Load necessary modules and configurations.

  1. Build Script Commands:

Define command-line options and functionalities for various build commands such as configuring a board, compiling a vehicle, enabling/disabling features, etc.

  1. Autoconfiguration:

Implement autoconfiguration features to trigger reconfiguration when necessary.

  1. Preparation for Board Configuration:

Set the variant build commands according to the selected board.
Define initialization tasks.

  1. Build Script Options:

Define various build options and configurations, such as enabling/disabling features, specifying toolchains, etc.

  1. Collect Autoconfig Files:

Collect autoconfiguration files from modules for hashing.

  1. Configure Method:

Implement the configuration process based on the specified options.

  1. Generate Task List:

Generate a task list for different build targets and configurations.

  1. Build Board Configuration:

Configure the build based on the selected board.

  1. Configure Method for Specific Build Options:

Implement specific configuration options, e.g., enabling/disabling features, setting default parameters, etc.

  1. Collecting Directories to Recurse:

Determine directories to recurse during the build process.

  1. Build Dynamic Sources:

Build dynamic sources such as MAVLink and DroneCAN.

  1. Build Common Task Generators:

Build common task generators shared by all programs and examples.

  1. Recursion for Subdirectories:

Recurse into subdirectories for building programs, tests, benchmarks, etc.

  1. Load Pre-Build Function:

Allow for a pre_build() function in build modules.

  1. Build Post Functions:

Execute post functions after the build, such as test summaries or submodule updates.

  1. Build Command Definitions:

Define custom build commands such as ‘check’, ‘check-all’, and specific board builds.

  1. Local Install and Rsync Contexts:

Implement custom build contexts for local installation and rsync.

5.3 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.4 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:
        bld.env.LINKFLAGS += ['-Wl,--wrap,%s' % w]

6. 总结

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

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

7. 参考资料

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

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐