maint: add a syntax-check rule to check for vulnerable Makefile.in
[gnulib.git] / top / maint.mk
1 # -*-Makefile-*-
2 # This Makefile fragment tries to be general-purpose enough to be
3 # used by many projects via the gnulib maintainer-makefile module.
4
5 ## Copyright (C) 2001-2010 Free Software Foundation, Inc.
6 ##
7 ## This program is free software: you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation, either version 3 of the License, or
10 ## (at your option) any later version.
11 ##
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 ## GNU General Public License for more details.
16 ##
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 # This is reported not to work with make-3.79.1
21 # ME := $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
22 ME := maint.mk
23
24 # Override this in cfg.mk if you use a non-standard build-aux directory.
25 build_aux ?= $(srcdir)/build-aux
26
27 # Do not save the original name or timestamp in the .tar.gz file.
28 # Use --rsyncable if available.
29 gzip_rsyncable := \
30   $(shell gzip --help 2>/dev/null|grep rsyncable >/dev/null && echo --rsyncable)
31 GZIP_ENV = '--no-name --best $(gzip_rsyncable)'
32
33 GIT = git
34 VC = $(GIT)
35 VC-tag = git tag -s -m '$(VERSION)' -u '$(gpg_key_ID)'
36
37 VC_LIST = $(build_aux)/vc-list-files -C $(srcdir)
38
39 # You can override this variable in cfg.mk to set your own regexp
40 # matching files to ignore.
41 VC_LIST_ALWAYS_EXCLUDE_REGEX ?= ^$$
42
43 # This is to preprocess robustly the output of $(VC_LIST), so that even
44 # when $(srcdir) is a pathological name like "....", the leading sed command
45 # removes only the intended prefix.
46 _dot_escaped_srcdir = $(subst .,\.,$(srcdir))
47
48 # Post-process $(VC_LIST) output, prepending $(srcdir)/, but only
49 # when $(srcdir) is not ".".
50 ifeq ($(srcdir),.)
51 _prepend_srcdir_prefix =
52 else
53 _prepend_srcdir_prefix = | sed 's|^|$(srcdir)/|'
54 endif
55
56 # In order to be able to consistently filter "."-relative names,
57 # (i.e., with no $(srcdir) prefix), this definition is careful to
58 # remove any $(srcdir) prefix, and to restore what it removes.
59 VC_LIST_EXCEPT = \
60   $(VC_LIST) | sed 's|^$(_dot_escaped_srcdir)/||' \
61         | if test -f $(srcdir)/.x-$@; then grep -vEf $(srcdir)/.x-$@; \
62           else grep -Ev -e "$${VC_LIST_EXCEPT_DEFAULT-ChangeLog}"; fi \
63         | grep -Ev -e '$(VC_LIST_ALWAYS_EXCLUDE_REGEX)' \
64         $(_prepend_srcdir_prefix)
65
66 ifeq ($(origin prev_version_file), undefined)
67   prev_version_file = $(srcdir)/.prev-version
68 endif
69
70 PREV_VERSION := $(shell cat $(prev_version_file) 2>/dev/null)
71 VERSION_REGEXP = $(subst .,\.,$(VERSION))
72 PREV_VERSION_REGEXP = $(subst .,\.,$(PREV_VERSION))
73
74 ifeq ($(VC),$(GIT))
75 this-vc-tag = v$(VERSION)
76 this-vc-tag-regexp = v$(VERSION_REGEXP)
77 else
78 tag-package = $(shell echo "$(PACKAGE)" | tr '[:lower:]' '[:upper:]')
79 tag-this-version = $(subst .,_,$(VERSION))
80 this-vc-tag = $(tag-package)-$(tag-this-version)
81 this-vc-tag-regexp = $(this-vc-tag)
82 endif
83 my_distdir = $(PACKAGE)-$(VERSION)
84
85 # Old releases are stored here.
86 release_archive_dir ?= ../release
87
88 # Override gnu_rel_host and url_dir_list in cfg.mk if these are not right.
89 # Use alpha.gnu.org for alpha and beta releases.
90 # Use ftp.gnu.org for stable releases.
91 gnu_ftp_host-alpha = alpha.gnu.org
92 gnu_ftp_host-beta = alpha.gnu.org
93 gnu_ftp_host-stable = ftp.gnu.org
94 gnu_rel_host ?= $(gnu_ftp_host-$(RELEASE_TYPE))
95
96 ifeq ($(gnu_rel_host),ftp.gnu.org)
97 url_dir_list ?= http://ftpmirror.gnu.org/$(PACKAGE)
98 else
99 url_dir_list ?= ftp://$(gnu_rel_host)/gnu/$(PACKAGE)
100 endif
101
102 # Override this in cfg.mk if you are using a different format in your
103 # NEWS file.
104 today = $(shell date +%Y-%m-%d)
105 news-check-regexp ?= '^\*.* $(VERSION_REGEXP) \($(today)\)'
106
107 # Prevent programs like 'sort' from considering distinct strings to be equal.
108 # Doing it here saves us from having to set LC_ALL elsewhere in this file.
109 export LC_ALL = C
110
111 ## --------------- ##
112 ## Sanity checks.  ##
113 ## --------------- ##
114
115 _cfg_mk := $(shell test -f $(srcdir)/cfg.mk && echo '$(srcdir)/cfg.mk')
116
117 # Collect the names of rules starting with `sc_'.
118 syntax-check-rules := $(sort $(shell sed -n 's/^\(sc_[a-zA-Z0-9_-]*\):.*/\1/p' \
119                         $(srcdir)/$(ME) $(_cfg_mk)))
120 .PHONY: $(syntax-check-rules)
121
122 local-checks-available = \
123   $(syntax-check-rules)
124 .PHONY: $(local-checks-available)
125
126 # Arrange to print the name of each syntax-checking rule just before running it.
127 $(syntax-check-rules): %: %.m
128 $(patsubst %, %.m, $(syntax-check-rules)):
129         @echo $(patsubst sc_%.m, %, $@)
130
131 local-check := $(filter-out $(local-checks-to-skip), $(local-checks-available))
132
133 syntax-check: $(local-check)
134 #       @grep -nE '#  *include <(limits|std(def|arg|bool))\.h>'         \
135 #           $$(find -type f -name '*.[chly]') &&                        \
136 #         { echo '$(ME): found conditional include' 1>&2;               \
137 #           exit 1; } || :
138
139 #       grep -nE '^#  *include <(string|stdlib)\.h>'                    \
140 #           $(srcdir)/{lib,src}/*.[chy] &&                              \
141 #         { echo '$(ME): FIXME' 1>&2;                                   \
142 #           exit 1; } || :
143 # FIXME: don't allow `#include .strings\.h' anywhere
144
145 # By default, _prohibit_regexp does not ignore case.
146 export ignore_case =
147 _ignore_case = $$(test -n "$$ignore_case" && echo -i || :)
148
149 # There are many rules below that prohibit constructs in this package.
150 # If the offending construct can be matched with a grep-E-style regexp,
151 # use this macro.  The shell variables "re" and "msg" must be defined.
152 define _prohibit_regexp
153   dummy=; : so we do not need a semicolon before each use;              \
154   test "x$$re" != x || { echo '$(ME): re not defined' 1>&2; exit 1; };  \
155   test "x$$msg" != x || { echo '$(ME): msg not defined' 1>&2; exit 1; };\
156   grep $(_ignore_case) -nE "$$re" $$($(VC_LIST_EXCEPT)) &&              \
157     { echo '$(ME): '"$$msg" 1>&2; exit 1; } || :
158 endef
159
160 sc_avoid_if_before_free:
161         @$(build_aux)/useless-if-before-free                            \
162                 $(useless_free_options)                                 \
163             $$($(VC_LIST_EXCEPT) | grep -v useless-if-before-free) &&   \
164           { echo '$(ME): found useless "if" before "free" above' 1>&2;  \
165             exit 1; } || :
166
167 sc_cast_of_argument_to_free:
168         @re='\<free *\( *\(' msg='don'\''t cast free argument'          \
169           $(_prohibit_regexp)
170
171 sc_cast_of_x_alloc_return_value:
172         @re='\*\) *x(m|c|re)alloc\>'                                    \
173         msg='don'\''t cast x*alloc return value'                        \
174           $(_prohibit_regexp)
175
176 sc_cast_of_alloca_return_value:
177         @re='\*\) *alloca\>' msg='don'\''t cast alloca return value'    \
178           $(_prohibit_regexp)
179
180 sc_space_tab:
181         @re='[ ]        ' msg='found SPACE-TAB sequence; remove the SPACE' \
182           $(_prohibit_regexp)
183
184 # Don't use *scanf or the old ato* functions in `real' code.
185 # They provide no error checking mechanism.
186 # Instead, use strto* functions.
187 sc_prohibit_atoi_atof:
188         @re='\<([fs]?scanf|ato([filq]|ll)) *\('                         \
189         msg='do not use *scan''f, ato''f, ato''i, ato''l, ato''ll or ato''q' \
190           $(_prohibit_regexp)
191
192 # Use STREQ rather than comparing strcmp == 0, or != 0.
193 sc_prohibit_strcmp:
194         @grep -nE '! *str''cmp *\(|\<str''cmp *\([^)]+\) *=='           \
195             $$($(VC_LIST_EXCEPT))                                       \
196           | grep -vE ':# *define STREQ\(' &&                            \
197           { echo '$(ME): use STREQ in place of the above uses of str''cmp' \
198                 1>&2; exit 1; } || :
199
200 # Pass EXIT_*, not number, to usage, exit, and error (when exiting)
201 # Convert all uses automatically, via these two commands:
202 # git grep -l '\<exit *(1)' \
203 #  | grep -vEf .x-sc_prohibit_magic_number_exit \
204 #  | xargs --no-run-if-empty \
205 #      perl -pi -e 's/(^|[^.])\b(exit ?)\(1\)/$1$2(EXIT_FAILURE)/'
206 # git grep -l '\<exit *(0)' \
207 #  | grep -vEf .x-sc_prohibit_magic_number_exit \
208 #  | xargs --no-run-if-empty \
209 #      perl -pi -e 's/(^|[^.])\b(exit ?)\(0\)/$1$2(EXIT_SUCCESS)/'
210 sc_prohibit_magic_number_exit:
211         @re='(^|[^.])\<(usage|exit) ?\([0-9]|\<error ?\([1-9][0-9]*,'   \
212         msg='use EXIT_* values rather than magic number'                \
213           $(_prohibit_regexp)
214
215 # Using EXIT_SUCCESS as the first argument to error is misleading,
216 # since when that parameter is 0, error does not exit.  Use `0' instead.
217 sc_error_exit_success:
218         @grep -nE 'error \(EXIT_SUCCESS,'                               \
219             $$($(VC_LIST_EXCEPT) | grep -E '\.[chly]$$') &&             \
220           { echo '$(ME): found error (EXIT_SUCCESS' 1>&2; exit 1; } || :
221
222 # `FATAL:' should be fully upper-cased in error messages
223 # `WARNING:' should be fully upper-cased, or fully lower-cased
224 sc_error_message_warn_fatal:
225         @grep -nEA2 '[^rp]error \(' $$($(VC_LIST_EXCEPT))               \
226             | grep -E '"Warning|"Fatal|"fatal' &&                       \
227           { echo '$(ME): use FATAL, WARNING or warning' 1>&2;           \
228             exit 1; } || :
229
230 # Error messages should not start with a capital letter
231 sc_error_message_uppercase:
232         @grep -nEA2 '[^rp]error \(' $$($(VC_LIST_EXCEPT))               \
233             | grep -E '"[A-Z]'                                          \
234             | grep -vE '"FATAL|"WARNING|"Java|"C#|PRIuMAX' &&           \
235           { echo '$(ME): found capitalized error message' 1>&2;         \
236             exit 1; } || :
237
238 # Error messages should not end with a period
239 sc_error_message_period:
240         @grep -nEA2 '[^rp]error \(' $$($(VC_LIST_EXCEPT))               \
241             | grep -E '[^."]\."' &&                                     \
242           { echo '$(ME): found error message ending in period' 1>&2;    \
243             exit 1; } || :
244
245 sc_file_system:
246         @re=file''system ignore_case=1                                  \
247         msg='found use of "file''system"; spell it "file system"'       \
248           $(_prohibit_regexp)
249
250 # Don't use cpp tests of this symbol.  All code assumes config.h is included.
251 sc_prohibit_have_config_h:
252         @grep -n '^# *if.*HAVE''_CONFIG_H' $$($(VC_LIST_EXCEPT)) &&     \
253           { echo '$(ME): found use of HAVE''_CONFIG_H; remove'          \
254                 1>&2; exit 1; } || :
255
256 # Nearly all .c files must include <config.h>.  However, we also permit this
257 # via inclusion of a package-specific header, if cfg.mk specified one.
258 # config_h_header must be suitable for grep -E.
259 config_h_header ?= <config\.h>
260 sc_require_config_h:
261         @if $(VC_LIST_EXCEPT) | grep -l '\.c$$' > /dev/null; then       \
262           grep -EL '^# *include $(config_h_header)'                     \
263                 $$($(VC_LIST_EXCEPT) | grep '\.c$$')                    \
264               | grep . &&                                               \
265           { echo '$(ME): the above files do not include <config.h>'     \
266                 1>&2; exit 1; } || :;                                   \
267         else :;                                                         \
268         fi
269
270 # You must include <config.h> before including any other header file.
271 # This can possibly be via a package-specific header, if given by cfg.mk.
272 sc_require_config_h_first:
273         @if $(VC_LIST_EXCEPT) | grep -l '\.c$$' > /dev/null; then       \
274           fail=0;                                                       \
275           for i in $$($(VC_LIST_EXCEPT) | grep '\.c$$'); do             \
276             grep '^# *include\>' $$i | sed 1q                           \
277                 | grep -E '^# *include $(config_h_header)' > /dev/null  \
278               || { echo $$i; fail=1; };                                 \
279           done;                                                         \
280           test $$fail = 1 &&                                            \
281             { echo '$(ME): the above files include some other header'   \
282                 'before <config.h>' 1>&2; exit 1; } || :;               \
283         else :;                                                         \
284         fi
285
286 sc_prohibit_HAVE_MBRTOWC:
287         @re='\bHAVE_MBRTOWC\b' msg="do not use $$re; it is always defined" \
288           $(_prohibit_regexp)
289
290 # To use this "command" macro, you must first define two shell variables:
291 # h: the header, enclosed in <> or ""
292 # re: a regular expression that matches IFF something provided by $h is used.
293 define _header_without_use
294   dummy=; : so we do not need a semicolon before each use;              \
295   h_esc=`echo "$$h"|sed 's/\./\\\\./g'`;                                \
296   if $(VC_LIST_EXCEPT) | grep -l '\.c$$' > /dev/null; then              \
297     files=$$(grep -l '^# *include '"$$h_esc"                            \
298              $$($(VC_LIST_EXCEPT) | grep '\.c$$')) &&                   \
299     grep -LE "$$re" $$files | grep . &&                                 \
300       { echo "$(ME): the above files include $$h but don't use it"      \
301         1>&2; exit 1; } || :;                                           \
302   else :;                                                               \
303   fi
304 endef
305
306 # Prohibit the inclusion of assert.h without an actual use of assert.
307 sc_prohibit_assert_without_use:
308         @h='<assert.h>' re='\<assert *\(' $(_header_without_use)
309
310 # Prohibit the inclusion of close-stream.h without an actual use.
311 sc_prohibit_close_stream_without_use:
312         @h='"close-stream.h"' re='\<close_stream *\(' $(_header_without_use)
313
314 # Prohibit the inclusion of getopt.h without an actual use.
315 sc_prohibit_getopt_without_use:
316         @h='<getopt.h>' re='\<getopt(_long)? *\(' $(_header_without_use)
317
318 # Don't include quotearg.h unless you use one of its functions.
319 sc_prohibit_quotearg_without_use:
320         @h='"quotearg.h"' re='\<quotearg(_[^ ]+)? *\(' $(_header_without_use)
321
322 # Don't include quote.h unless you use one of its functions.
323 sc_prohibit_quote_without_use:
324         @h='"quote.h"' re='\<quote(_n)? *\(' $(_header_without_use)
325
326 # Don't include this header unless you use one of its functions.
327 sc_prohibit_long_options_without_use:
328         @h='"long-options.h"' re='\<parse_long_options *\(' \
329           $(_header_without_use)
330
331 # Don't include this header unless you use one of its functions.
332 sc_prohibit_inttostr_without_use:
333         @h='"inttostr.h"' re='\<(off|[iu]max|uint)tostr *\(' \
334           $(_header_without_use)
335
336 # Don't include this header unless you use one of its functions.
337 sc_prohibit_error_without_use:
338         @h='"error.h"' \
339         re='\<error(_at_line|_print_progname|_one_per_line|_message_count)? *\('\
340           $(_header_without_use)
341
342 # Don't include xalloc.h unless you use one of its functions.
343 # Consider these symbols:
344 # perl -lne '/^# *define (\w+)\(/ and print $1' lib/xalloc.h|grep -v '^__';
345 # perl -lne '/^(?:extern )?(?:void|char) \*?(\w+) \(/ and print $1' lib/xalloc.h
346 # Divide into two sets on case, and filter each through this:
347 # | sort | perl -MRegexp::Assemble -le \
348 #  'print Regexp::Assemble->new(file => "/dev/stdin")->as_string'|sed 's/\?://g'
349 # Note this was produced by the above:
350 # _xa1 = \
351 #x(((2n?)?re|c(har)?|n(re|m)|z)alloc|alloc_(oversized|die)|m(alloc|emdup)|strdup)
352 # But we can do better, in at least two ways:
353 # 1) take advantage of two "dup"-suffixed strings:
354 # x(((2n?)?re|c(har)?|n(re|m)|[mz])alloc|alloc_(oversized|die)|(mem|str)dup)
355 # 2) notice that "c(har)?|[mz]" is equivalent to the shorter and more readable
356 # "char|[cmz]"
357 # x(((2n?)?re|char|n(re|m)|[cmz])alloc|alloc_(oversized|die)|(mem|str)dup)
358 _xa1 = x(((2n?)?re|char|n(re|m)|[cmz])alloc|alloc_(oversized|die)|(mem|str)dup)
359 _xa2 = X([CZ]|N?M)ALLOC
360 sc_prohibit_xalloc_without_use:
361         @h='"xalloc.h"' \
362         re='\<($(_xa1)|$(_xa2)) *\('\
363           $(_header_without_use)
364
365 sc_prohibit_safe_read_without_use:
366         @h='"safe-read.h"' re='(\<SAFE_READ_ERROR\>|\<safe_read *\()' \
367           $(_header_without_use)
368
369 sc_prohibit_argmatch_without_use:
370         @h='"argmatch.h"' \
371         re='(\<(ARRAY_CARDINALITY|X?ARGMATCH(|_TO_ARGUMENT|_VERIFY))\>|\<argmatch(_exit_fn|_(in)?valid) *\()' \
372           $(_header_without_use)
373
374 sc_prohibit_canonicalize_without_use:
375         @h='"canonicalize.h"' \
376         re='CAN_(EXISTING|ALL_BUT_LAST|MISSING)|canonicalize_(mode_t|filename_mode)' \
377           $(_header_without_use)
378
379 sc_prohibit_root_dev_ino_without_use:
380         @h='"root-dev-ino.h"' \
381         re='(\<ROOT_DEV_INO_(CHECK|WARN)\>|\<get_root_dev_ino *\()' \
382           $(_header_without_use)
383
384 sc_prohibit_openat_without_use:
385         @h='"openat.h"' \
386         re='\<(openat_(permissive|needs_fchdir|(save|restore)_fail)|l?(stat|ch(own|mod))at|(euid)?accessat)\>' \
387           $(_header_without_use)
388
389 # Prohibit the inclusion of c-ctype.h without an actual use.
390 ctype_re = isalnum|isalpha|isascii|isblank|iscntrl|isdigit|isgraph|islower\
391 |isprint|ispunct|isspace|isupper|isxdigit|tolower|toupper
392 sc_prohibit_c_ctype_without_use:
393         @h='[<"]c-ctype.h[">]' re='\<c_($(ctype_re)) *\(' $(_header_without_use)
394
395 _empty =
396 _sp = $(_empty) $(_empty)
397 # The following list was generated by running:
398 # man signal.h|col -b|perl -ne '/bsd_signal.*;/.../sigwaitinfo.*;/ and print' \
399 #   | perl -lne '/^\s+(?:int|void).*?(\w+).*/ and print $1' | fmt
400 _sig_functions = \
401   bsd_signal kill killpg pthread_kill pthread_sigmask raise sigaction \
402   sigaddset sigaltstack sigdelset sigemptyset sigfillset sighold sigignore \
403   siginterrupt sigismember signal sigpause sigpending sigprocmask sigqueue \
404   sigrelse sigset sigsuspend sigtimedwait sigwait sigwaitinfo
405 _sig_function_re = $(subst $(_sp),|,$(strip $(_sig_functions)))
406 # The following were extracted from "man signal.h" manually.
407 _sig_types_and_consts =                                                 \
408   MINSIGSTKSZ SA_NOCLDSTOP SA_NOCLDWAIT SA_NODEFER SA_ONSTACK           \
409   SA_RESETHAND SA_RESTART SA_SIGINFO SIGEV_NONE SIGEV_SIGNAL            \
410   SIGEV_THREAD SIGSTKSZ SIG_BLOCK SIG_SETMASK SIG_UNBLOCK SS_DISABLE    \
411   SS_ONSTACK mcontext_t pid_t sig_atomic_t sigevent siginfo_t sigset_t  \
412   sigstack sigval stack_t ucontext_t
413 # generated via this:
414 # perl -lne '/^#ifdef (SIG\w+)/ and print $1' lib/sig2str.c|sort -u|fmt -70
415 _sig_names =                                                            \
416   SIGABRT SIGALRM SIGALRM1 SIGBUS SIGCANCEL SIGCHLD SIGCLD SIGCONT      \
417   SIGDANGER SIGDIL SIGEMT SIGFPE SIGFREEZE SIGGRANT SIGHUP SIGILL       \
418   SIGINFO SIGINT SIGIO SIGIOT SIGKAP SIGKILL SIGKILLTHR SIGLOST SIGLWP  \
419   SIGMIGRATE SIGMSG SIGPHONE SIGPIPE SIGPOLL SIGPRE SIGPROF SIGPWR      \
420   SIGQUIT SIGRETRACT SIGSAK SIGSEGV SIGSOUND SIGSTKFLT SIGSTOP SIGSYS   \
421   SIGTERM SIGTHAW SIGTRAP SIGTSTP SIGTTIN SIGTTOU SIGURG SIGUSR1        \
422   SIGUSR2 SIGVIRT SIGVTALRM SIGWAITING SIGWINCH SIGWIND SIGWINDOW       \
423   SIGXCPU SIGXFSZ
424 _sig_syms_re = $(subst $(_sp),|,$(strip $(_sig_names) $(_sig_types_and_consts)))
425
426 # Prohibit the inclusion of signal.h without an actual use.
427 sc_prohibit_signal_without_use:
428         @h='<signal.h>'                                                 \
429         re='\<($(_sig_function_re)) *\(|\<($(_sig_syms_re))\>'          \
430           $(_header_without_use)
431
432 sc_obsolete_symbols:
433         @re='\<(HAVE''_FCNTL_H|O''_NDELAY)\>'                           \
434         msg='do not use HAVE''_FCNTL_H or O'_NDELAY                     \
435           $(_prohibit_regexp)
436
437 # FIXME: warn about definitions of EXIT_FAILURE, EXIT_SUCCESS, STREQ
438
439 # Each nonempty ChangeLog line must start with a year number, or a TAB.
440 sc_changelog:
441         @if $(VC_LIST_EXCEPT) | grep -l '^ChangeLog$$' >/dev/null; then \
442           grep -n '^[^12        ]'                                      \
443             $$($(VC_LIST_EXCEPT) | grep '^ChangeLog$$') &&              \
444           { echo '$(ME): found unexpected prefix in a ChangeLog' 1>&2;  \
445             exit 1; } || :;                                             \
446         fi
447
448 # Ensure that each .c file containing a "main" function also
449 # calls set_program_name.
450 sc_program_name:
451         @if $(VC_LIST_EXCEPT) | grep -l '\.c$$' > /dev/null; then       \
452           files=$$(grep -l '^main *(' $$($(VC_LIST_EXCEPT) | grep '\.c$$')); \
453           grep -LE 'set_program_name *\(m?argv\[0\]\);' $$files         \
454               | grep . &&                                               \
455           { echo '$(ME): the above files do not call set_program_name'  \
456                 1>&2; exit 1; } || :;                                   \
457         else :;                                                         \
458         fi
459
460 # Require that the final line of each test-lib.sh-using test be this one:
461 # Exit $fail
462 # Note: this test requires GNU grep's --label= option.
463 Exit_witness_file ?= tests/test-lib.sh
464 Exit_base := $(notdir $(Exit_witness_file))
465 sc_require_test_exit_idiom:
466         @if test -f $(srcdir)/$(Exit_witness_file); then                \
467           die=0;                                                        \
468           for i in $$(grep -l -F 'srcdir/$(Exit_base)'                  \
469                 $$($(VC_LIST) tests)); do                               \
470             tail -n1 $$i | grep '^Exit .' > /dev/null                   \
471               && : || { die=1; echo $$i; }                              \
472           done;                                                         \
473           test $$die = 1 &&                                             \
474             { echo 1>&2 '$(ME): the final line in each of the above is not:'; \
475               echo 1>&2 'Exit something';                               \
476               exit 1; } || :;                                           \
477         fi
478
479 sc_the_the:
480         @re='\<the ''the\>'                                             \
481         ignore_case=1 msg='found use of "the ''the";'                   \
482           $(_prohibit_regexp)
483
484 sc_trailing_blank:
485         @re='[   ]$$'                                                   \
486         msg='found trailing blank(s)'                                   \
487           $(_prohibit_regexp)
488
489 # Match lines like the following, but where there is only one space
490 # between the options and the description:
491 #   -D, --all-repeated[=delimit-method]  print all duplicate lines\n
492 longopt_re = --[a-z][0-9A-Za-z-]*(\[?=[0-9A-Za-z-]*\]?)?
493 sc_two_space_separator_in_usage:
494         @grep -nE '^   *(-[A-Za-z],)? $(longopt_re) [^ ].*\\$$'         \
495             $$($(VC_LIST_EXCEPT)) &&                                    \
496           { echo "$(ME): help2man requires at least two spaces between"; \
497             echo "$(ME): an option and its description";                \
498                 1>&2; exit 1; } || :
499
500 # Look for diagnostics that aren't marked for translation.
501 # This won't find any for which error's format string is on a separate line.
502 sc_unmarked_diagnostics:
503         @grep -nE                                                       \
504             '\<error \([^"]*"[^"]*[a-z]{3}' $$($(VC_LIST_EXCEPT))       \
505           | grep -v '_''(' &&                                           \
506           { echo '$(ME): found unmarked diagnostic(s)' 1>&2;            \
507             exit 1; } || :
508
509 # Avoid useless parentheses like those in this example:
510 # #if defined (SYMBOL) || defined (SYM2)
511 sc_useless_cpp_parens:
512         @grep -n '^# *if .*defined *(' $$($(VC_LIST_EXCEPT)) &&         \
513           { echo '$(ME): found useless parentheses in cpp directive'    \
514                 1>&2; exit 1; } || :
515
516 # Require the latest GPL.
517 sc_GPL_version:
518         @re='either ''version [^3]' msg='GPL vN, N!=3'                  \
519           $(_prohibit_regexp)
520
521 # Require the latest GFDL.  Two regexp, since some .texi files end up
522 # line wrapping between 'Free Documentation License,' and 'Version'.
523 _GFDL_regexp = (Free ''Documentation.*Version 1\.[^3]|Version 1\.[^3] or any)
524 sc_GFDL_version:
525         @re='$(_GFDL_regexp)' msg='GFDL vN, N!=3'                       \
526           $(_prohibit_regexp)
527
528 cvs_keywords = \
529   Author|Date|Header|Id|Name|Locker|Log|RCSfile|Revision|Source|State
530
531 sc_prohibit_cvs_keyword:
532         @re='\$$($(cvs_keywords))\$$'                                   \
533             msg='do not use CVS keyword expansion'                      \
534           $(_prohibit_regexp)
535
536 # Make sure we don't use st_blocks.  Use ST_NBLOCKS instead.
537 # This is a bit of a kludge, since it prevents use of the string
538 # even in comments, but for now it does the job with no false positives.
539 sc_prohibit_stat_st_blocks:
540         @re='[.>]st_blocks' msg='do not use st_blocks; use ST_NBLOCKS'  \
541           $(_prohibit_regexp)
542
543 # Make sure we don't define any S_IS* macros in src/*.c files.
544 # They're already defined via gnulib's sys/stat.h replacement.
545 sc_prohibit_S_IS_definition:
546         @re='^ *# *define  *S_IS'                                       \
547         msg='do not define S_IS* macros; include <sys/stat.h>'          \
548           $(_prohibit_regexp)
549
550 # Each program that uses proper_name_utf8 must link with one of the
551 # ICONV libraries.  Otherwise, some ICONV library must appear in LDADD.
552 # The perl -0777 invocation below extracts the possibly-multi-line
553 # definition of LDADD from the appropriate Makefile.am and exits 0
554 # when it contains "ICONV".
555 sc_proper_name_utf8_requires_ICONV:
556         @progs=$$(grep -l 'proper_name_utf8 ''("' $$($(VC_LIST_EXCEPT)));\
557         if test "x$$progs" != x; then                                   \
558           fail=0;                                                       \
559           for p in $$progs; do                                          \
560             dir=$$(dirname "$$p");                                      \
561             perl -0777                                                  \
562               -ne 'exit !(/^LDADD =(.+?[^\\]\n)/ms && $$1 =~ /ICONV/)'  \
563               $$dir/Makefile.am && continue;                            \
564             base=$$(basename "$$p" .c);                                 \
565             grep "$${base}_LDADD.*ICONV)" $$dir/Makefile.am > /dev/null \
566               || { fail=1; echo 1>&2 "$(ME): $$p uses proper_name_utf8"; }; \
567           done;                                                         \
568           test $$fail = 1 &&                                            \
569             { echo 1>&2 '$(ME): the above do not link with any ICONV library'; \
570               exit 1; } || :;                                           \
571         fi
572
573 # Warn about "c0nst struct Foo const foo[]",
574 # but not about "char const *const foo" or "#define const const".
575 sc_redundant_const:
576         @re='\bconst\b[[:space:][:alnum:]]{2,}\bconst\b'                \
577         msg='redundant "const" in declarations'                         \
578           $(_prohibit_regexp)
579
580 sc_const_long_option:
581         @grep '^ *static.*struct option ' $$($(VC_LIST_EXCEPT))         \
582           | grep -Ev 'const struct option|struct option const' && {     \
583               echo 1>&2 '$(ME): add "const" to the above declarations'; \
584               exit 1; } || :
585
586 NEWS_hash =                                                             \
587   $$(sed -n '/^\*.* $(PREV_VERSION_REGEXP) ([0-9-]*)/,$$p'              \
588        $(srcdir)/NEWS                                                   \
589      | perl -0777 -pe                                                   \
590         's/^Copyright.+?Free\sSoftware\sFoundation,\sInc\.\n//ms'       \
591      | md5sum -                                                         \
592      | sed 's/ .*//')
593
594 # Ensure that we don't accidentally insert an entry into an old NEWS block.
595 sc_immutable_NEWS:
596         @if test -f $(srcdir)/NEWS; then                                \
597           test "$(NEWS_hash)" = '$(old_NEWS_hash)' && : ||              \
598             { echo '$(ME): you have modified old NEWS' 1>&2; exit 1; }; \
599         fi
600
601 # Update the hash stored above.  Do this after each release and
602 # for any corrections to old entries.
603 update-NEWS-hash: NEWS
604         perl -pi -e 's/^(old_NEWS_hash[ \t]+:?=[ \t]+).*/$${1}'"$(NEWS_hash)/" \
605           $(srcdir)/cfg.mk
606
607 # Ensure that we use only the standard $(VAR) notation,
608 # not @...@ in Makefile.am, now that we can rely on automake
609 # to emit a definition for each substituted variable.
610 # We use perl rather than "grep -nE ..." to exempt a single
611 # use of an @...@-delimited variable name in src/Makefile.am.
612 # Allow the package to add exceptions via a hook in cfg.mk;
613 # for example, @PRAGMA_SYSTEM_HEADER@ can be permitted by
614 # setting this to ' && !/PRAGMA_SYSTEM_HEADER/'.
615 _makefile_at_at_check_exceptions ?=
616 sc_makefile_at_at_check:
617         @perl -ne '/\@[A-Z_0-9]+\@/'$(_makefile_at_at_check_exceptions) \
618           -e 'and (print "$$ARGV:$$.: $$_"), $$m=1; END {exit !$$m}'    \
619             $$($(VC_LIST_EXCEPT) | grep -E '(^|/)Makefile\.am$$')       \
620           && { echo '$(ME): use $$(...), not @...@' 1>&2; exit 1; } || :
621
622 news-check: NEWS
623         if head $(srcdir)/NEWS | grep -E $(news-check-regexp)           \
624             >/dev/null; then                                            \
625           :;                                                            \
626         else                                                            \
627           echo 'NEWS: $$(news-check-regexp) failed to match' 1>&2;      \
628           exit 1;                                                       \
629         fi
630
631 sc_makefile_TAB_only_indentation:
632         @grep -nE '^    [ ]{8}'                                         \
633             $$($(VC_LIST_EXCEPT) | grep -E 'akefile|\.mk$$')            \
634           && { echo '$(ME): found TAB-8-space indentation' 1>&2;        \
635                exit 1; } || :
636
637 sc_m4_quote_check:
638         @grep -nE '(AC_DEFINE(_UNQUOTED)?|AC_DEFUN)\([^[]'              \
639             $$($(VC_LIST_EXCEPT) | grep -E '(^configure\.ac|\.m4)$$')   \
640           && { echo '$(ME): quote the first arg to AC_DEF*' 1>&2;       \
641                exit 1; } || :
642
643 fix_po_file_diag = \
644 'you have changed the set of files with translatable diagnostics;\n\
645 apply the above patch\n'
646
647 # Verify that all source files using _() are listed in po/POTFILES.in.
648 po_file = po/POTFILES.in
649 sc_po_check:
650         @if test -f $(po_file); then                                    \
651           grep -E -v '^(#|$$)' $(po_file)                               \
652             | grep -v '^src/false\.c$$' | sort > $@-1;                  \
653           files=;                                                       \
654           for file in $$($(VC_LIST_EXCEPT)) lib/*.[ch]; do              \
655             test -r $$file || continue;                                 \
656             case $$file in                                              \
657               *.m4|*.mk) continue ;;                                    \
658               *.?|*.??) ;;                                              \
659               *) continue;;                                             \
660             esac;                                                       \
661             case $$file in                                              \
662             *.[ch])                                                     \
663               base=`expr " $$file" : ' \(.*\)\..'`;                     \
664               { test -f $$base.l || test -f $$base.y; } && continue;;   \
665             esac;                                                       \
666             files="$$files $$file";                                     \
667           done;                                                         \
668           grep -E -l '\b(N?_|gettext *)\([^)"]*("|$$)' $$files          \
669             | sort -u > $@-2;                                           \
670           diff -u -L $(po_file) -L $(po_file) $@-1 $@-2                 \
671             || { printf '$(ME): '$(fix_po_file_diag) 1>&2; exit 1; };   \
672           rm -f $@-1 $@-2;                                              \
673         fi
674
675 # Sometimes it is useful to change the PATH environment variable
676 # in Makefiles.  When doing so, it's better not to use the Unix-centric
677 # path separator of `:', but rather the automake-provided `$(PATH_SEPARATOR)'.
678 msg = '$(ME): Do not use `:'\'' above; use $$(PATH_SEPARATOR) instead'
679 sc_makefile_path_separator_check:
680         @grep -nE 'PATH[=].*:'                                          \
681             $$($(VC_LIST_EXCEPT) | grep -E 'akefile|\.mk$$')            \
682           && { echo $(msg) 1>&2; exit 1; } || :
683
684 # Check that `make alpha' will not fail at the end of the process.
685 writable-files:
686         if test -d $(release_archive_dir); then :; else                 \
687           for file in $(distdir).tar.gz                                 \
688                       $(release_archive_dir)/$(distdir).tar.gz; do      \
689             test -e $$file || continue;                                 \
690             test -w $$file                                              \
691               || { echo ERROR: $$file is not writable; fail=1; };       \
692           done;                                                         \
693           test "$$fail" && exit 1 || : ;                                \
694         fi
695
696 v_etc_file = lib/version-etc.c
697 sample-test = tests/sample-test
698 texi = doc/$(PACKAGE).texi
699 # Make sure that the copyright date in $(v_etc_file) is up to date.
700 # Do the same for the $(sample-test) and the main doc/.texi file.
701 sc_copyright_check:
702         @if test -f $(v_etc_file); then                                 \
703           grep 'enum { COPYRIGHT_YEAR = '$$(date +%Y)' };' $(v_etc_file) \
704             >/dev/null                                                  \
705           || { echo 'out of date copyright in $(v_etc_file); update it' 1>&2; \
706                exit 1; };                                               \
707         fi
708         @if test -f $(sample-test); then                                \
709           grep '# Copyright (C) '$$(date +%Y)' Free' $(sample-test)     \
710             >/dev/null                                                  \
711           || { echo 'out of date copyright in $(sample-test); update it' 1>&2; \
712                exit 1; };                                               \
713         fi
714         @if test -f $(texi); then                                       \
715           grep 'Copyright @copyright{} .*'$$(date +%Y)' Free' $(texi)   \
716             >/dev/null                                                  \
717           || { echo 'out of date copyright in $(texi); update it' 1>&2; \
718                exit 1; };                                               \
719         fi
720
721 # #if HAVE_... will evaluate to false for any non numeric string.
722 # That would be flagged by using -Wundef, however gnulib currently
723 # tests many undefined macros, and so we can't enable that option.
724 # So at least preclude common boolean strings as macro values.
725 sc_Wundef_boolean:
726         @grep -Ei '^#define.*(yes|no|true|false)$$' '$(CONFIG_INCLUDE)' && \
727           { echo 'Use 0 or 1 for macro values' 1>&2; exit 1; } || :
728
729 sc_vulnerable_makefile_CVE-2009-4029:
730         @files=$$(find $(srcdir) -name Makefile.in);                    \
731         if test -n "$$files"; then                                      \
732           grep -E                                                       \
733             'perm -777 -exec chmod a\+rwx|chmod 777 \$$\(distdir\)'     \
734             $$files &&                                                  \
735           { echo '$(ME): the above files are vulnerable; beware of'     \
736             'running "make dist*" rules, and upgrade to fixed automake' \
737             'see http://bugzilla.redhat.com/542609 for details'         \
738                 1>&2; exit 1; } || :;                                   \
739         else :;                                                         \
740         fi
741
742 vc-diff-check:
743         (unset CDPATH; cd $(srcdir) && $(VC) diff) > vc-diffs || :
744         if test -s vc-diffs; then                               \
745           cat vc-diffs;                                         \
746           echo "Some files are locally modified:" 1>&2;         \
747           exit 1;                                               \
748         else                                                    \
749           rm vc-diffs;                                          \
750         fi
751
752 rel-files = $(DIST_ARCHIVES)
753
754 gnulib_dir ?= $(srcdir)/gnulib
755 gnulib-version = $$(cd $(gnulib_dir) && git describe)
756 bootstrap-tools ?= autoconf,automake,gnulib
757
758 # If it's not already specified, derive the GPG key ID from
759 # the signed tag we've just applied to mark this release.
760 gpg_key_ID ?= \
761   $$(git cat-file tag v$(VERSION) > .ann-sig \
762      && gpgv .ann-sig - < /dev/null 2>&1 \
763           | sed -n '/.*key ID \([0-9A-F]*\)/s//\1/p'; rm -f .ann-sig)
764
765 announcement: NEWS ChangeLog $(rel-files)
766         @$(build_aux)/announce-gen                                      \
767             --release-type=$(RELEASE_TYPE)                              \
768             --package=$(PACKAGE)                                        \
769             --prev=$(PREV_VERSION)                                      \
770             --curr=$(VERSION)                                           \
771             --gpg-key-id=$(gpg_key_ID)                                  \
772             --news=$(srcdir)/NEWS                                       \
773             --bootstrap-tools=$(bootstrap-tools)                        \
774             --gnulib-version=$(gnulib-version)                          \
775             --no-print-checksums                                        \
776             $(addprefix --url-dir=, $(url_dir_list))
777
778 ## ---------------- ##
779 ## Updating files.  ##
780 ## ---------------- ##
781
782 ftp-gnu = ftp://ftp.gnu.org/gnu
783 www-gnu = http://www.gnu.org
784
785 emit_upload_commands:
786         @echo =====================================
787         @echo =====================================
788         @echo "$(build_aux)/gnupload $(GNUPLOADFLAGS) \\"
789         @echo "    --to $(gnu_rel_host):$(PACKAGE) \\"
790         @echo "  $(rel-files)"
791         @echo '# send the ~/announce-$(my_distdir) e-mail'
792         @echo =====================================
793         @echo =====================================
794
795 noteworthy = * Noteworthy changes in release ?.? (????-??-??) [?]
796 define emit-commit-log
797   printf '%s\n' 'post-release administrivia' '' \
798     '* NEWS: Add header line for next release.' \
799     '* .prev-version: Record previous version.' \
800     '* cfg.mk (old_NEWS_hash): Auto-update.'
801 endef
802
803 .PHONY: no-submodule-changes
804 no-submodule-changes:
805         if test -d $(srcdir)/.git; then                                 \
806           diff=$$(cd $(srcdir) && git submodule -q foreach              \
807                   git diff-index --name-only HEAD)                      \
808             || exit 1;                                                  \
809           case $$diff in '') ;;                                         \
810             *) echo '$(ME): submodule files are locally modified:';     \
811                 echo "$$diff"; exit 1;; esac;                           \
812         else                                                            \
813           : ;                                                           \
814         fi
815
816 .PHONY: alpha beta stable
817 ALL_RECURSIVE_TARGETS += alpha beta stable
818 alpha beta stable: $(local-check) writable-files no-submodule-changes
819         test $@ = stable                                                \
820           && { echo $(VERSION) | grep -E '^[0-9]+(\.[0-9]+)+$$'         \
821                || { echo "invalid version string: $(VERSION)" 1>&2; exit 1;};}\
822           || :
823         $(MAKE) vc-diff-check
824         $(MAKE) news-check
825         $(MAKE) distcheck
826         $(MAKE) dist XZ_OPT=-9ev
827         $(MAKE) $(release-prep-hook) RELEASE_TYPE=$@
828         $(MAKE) -s emit_upload_commands RELEASE_TYPE=$@
829
830 # Override this in cfg.mk if you follow different procedures.
831 release-prep-hook ?= release-prep
832
833 .PHONY: release-prep
834 release-prep:
835         case $$RELEASE_TYPE in alpha|beta|stable) ;; \
836           *) echo "invalid RELEASE_TYPE: $$RELEASE_TYPE" 1>&2; exit 1;; esac
837         $(MAKE) -s announcement > ~/announce-$(my_distdir)
838         if test -d $(release_archive_dir); then                 \
839           ln $(rel-files) $(release_archive_dir);               \
840           chmod a-w $(rel-files);                               \
841         fi
842         echo $(VERSION) > $(prev_version_file)
843         $(MAKE) update-NEWS-hash
844         perl -pi -e '$$. == 3 and print "$(noteworthy)\n\n\n"' NEWS
845         $(emit-commit-log) > .ci-msg
846         $(VC) commit -F .ci-msg -a
847         rm .ci-msg
848
849 .PHONY: web-manual
850 web-manual:
851         @test -z "$(manual_title)" \
852           && { echo define manual_title in cfg.mk 1>&2; exit 1; } || :
853         @cd '$(srcdir)/doc'; \
854           $(SHELL) ../build-aux/gendocs.sh -o '$(abs_builddir)/doc/manual' \
855              --email $(PACKAGE_BUGREPORT) $(PACKAGE) \
856             "$(PACKAGE_NAME) - $(manual_title)"
857         @echo " *** Upload the doc/manual directory to web-cvs."
858
859 # Code Coverage
860
861 init-coverage:
862         $(MAKE) $(AM_MAKEFLAGS) clean
863         lcov --directory . --zerocounters
864
865 COVERAGE_CCOPTS ?= "-g --coverage"
866 COVERAGE_OUT ?= doc/coverage
867
868 build-coverage:
869         $(MAKE) $(AM_MAKEFLAGS) CFLAGS=$(COVERAGE_CCOPTS) CXXFLAGS=$(COVERAGE_CCOPTS)
870         $(MAKE) $(AM_MAKEFLAGS) CFLAGS=$(COVERAGE_CCOPTS) CXXFLAGS=$(COVERAGE_CCOPTS) check
871         mkdir -p $(COVERAGE_OUT)
872         lcov --directory . --output-file $(COVERAGE_OUT)/$(PACKAGE).info \
873                 --capture
874
875 gen-coverage:
876         genhtml --output-directory $(COVERAGE_OUT) \
877                 $(COVERAGE_OUT)/$(PACKAGE).info \
878                 --highlight --frames --legend \
879                 --title "$(PACKAGE_NAME)"
880
881 coverage: init-coverage build-coverage gen-coverage
882
883 # Update gettext files.
884 PACKAGE ?= $(shell basename $(PWD))
885 PO_DOMAIN ?= $(PACKAGE)
886 POURL = http://translationproject.org/latest/$(PO_DOMAIN)/
887 PODIR ?= po
888 refresh-po:
889         rm -f $(PODIR)/*.po && \
890         echo "$(ME): getting translations into po (please ignore the robots.txt ERROR 404)..." && \
891         wget --no-verbose --directory-prefix $(PODIR) --no-directories --recursive --level 1 --accept .po --accept .po.1 $(POURL) && \
892         echo 'en@boldquot' > $(PODIR)/LINGUAS && \
893         echo 'en@quot' >> $(PODIR)/LINGUAS && \
894         ls $(PODIR)/*.po | sed 's/\.po//' | sed 's,$(PODIR)/,,' | sort >> $(PODIR)/LINGUAS
895
896 INDENT_SOURCES ?= $(C_SOURCES)
897 .PHONY: indent
898 indent:
899         indent $(INDENT_SOURCES)
900
901 # If you want to set UPDATE_COPYRIGHT_* environment variables,
902 # put the assignments in this variable.
903 update-copyright-env ?=
904
905 # Run this rule once per year (usually early in January)
906 # to update all FSF copyright year lists in your project.
907 # If you have an additional project-specific rule,
908 # add it in cfg.mk along with a line 'update-copyright: prereq'.
909 # By default, exclude all variants of COPYING; you can also
910 # add exemptions (such as ChangeLog..* for rotated change logs)
911 # in the file .x-update-copyright.
912 .PHONY: update-copyright
913 update-copyright:
914         grep -l -w Copyright                                             \
915           $$(export VC_LIST_EXCEPT_DEFAULT=COPYING && $(VC_LIST_EXCEPT)) \
916           | $(update-copyright-env) xargs $(build_aux)/$@