1#!/usr/bin/env python3
2#
3# Copyright (c) 2021 Nordic Semiconductor NA
4#
5# SPDX-License-Identifier: Apache-2.0
6
7"""Check minimal libc error numbers against newlib.
8
9This script loads the errno.h included in Zephyr's minimal libc and checks its
10contents against the SDK's newlib errno.h. This is done to ensure that both C
11libraries are aligned at all times.
12"""
13
14
15import os
16from pathlib import Path
17import re
18import sys
19
20def parse_errno(path):
21    with open(path, 'r') as f:
22        r = re.compile(r'^\s*#define\s+([A-Z]+)\s+([0-9]+)')
23        errnos = []
24        for line in f:
25            m = r.match(line)
26            if m:
27                errnos.append(m.groups())
28
29    return errnos
30
31def main():
32
33    minimal = Path("lib/libc/minimal/include/errno.h")
34    newlib = Path("arm-zephyr-eabi/arm-zephyr-eabi/include/sys/errno.h")
35
36    try:
37        minimal = os.environ['ZEPHYR_BASE'] / minimal
38        newlib = os.environ['ZEPHYR_SDK_INSTALL_DIR'] / newlib
39    except KeyError as e:
40        print(f'Environment variable missing: {e}', file=sys.stderr)
41        sys.exit(1)
42
43    minimal = parse_errno(minimal)
44    newlib = parse_errno(newlib)
45
46    for e in minimal:
47        if e[0] not in [x[0] for x in newlib] or e[1] != next(
48            filter(lambda _e: _e[0] == e[0], newlib))[1]:
49            print('Invalid entry in errno.h:', file=sys.stderr)
50            print(f'{e[0]} (with value {e[1]})', file=sys.stderr)
51            sys.exit(1)
52
53    print('errno.h validated correctly')
54
55if __name__ == "__main__":
56    main()
57