1#!/bin/sh
2
3# Copyright 2015 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7# Generates a header file with a named constant table made up of "name", value
8# entries by including several build target header files and emitting the list
9# of defines.  Use of the preprocessor is needed to recursively include all
10# relevant headers.
11
12set -e
13
14if [ $# -ne 1 ] && [ $# -ne 2 ]; then
15  echo "Usage: $(basename "$0") OUTFILE"
16  echo "Usage: $(basename "$0") CC OUTFILE"
17  exit 1
18fi
19
20if [ $# -eq 2 ]; then
21  CC="$1"
22  shift
23fi
24OUTFILE="$1"
25
26INCLUDES='
27#include <errno.h>
28#include <fcntl.h>
29#include <linux/prctl.h>
30#include <linux/sched.h>
31#include <stddef.h>
32#include <signal.h>
33#include <sys/stat.h>
34#include <sys/types.h>'
35
36# sed expression which extracts constants and converts them from:
37#   #define AT_FDWCD foo
38# to:
39# #ifdef AT_FDCWD
40#   { "AT_FDWCD", AT_FDCWD },
41# endif
42SED_MULTILINE='s@#define ([[:upper:]][[:upper:]0-9_]*).*@#ifdef \1\
43  { "\1", (unsigned long) \1 },\
44#endif  // \1@'
45
46# Passes the previous list of #includes to the C preprocessor and prints out
47# all #defines whose name is all-caps.  Excludes a few symbols that are known
48# macro functions that don't evaluate to a constant.
49cat <<-EOF > "${OUTFILE}"
50/* GENERATED BY MAKEFILE */
51$INCLUDES
52
53#include "libconstants.h"
54const struct constant_entry constant_table[] = {
55$(echo "$INCLUDES" | \
56  ${CC} -dD - -E | \
57  grep -E '^#define [[:upper:]][[:upper:]0-9_]*(\s)+[[:alnum:]]' | \
58  grep -Ev '(SIGRTMAX|SIGRTMIN|SIG_|NULL)' | \
59  sort -u | \
60  sed -Ee "${SED_MULTILINE}")
61  { NULL, 0 },
62};
63EOF
64