xref: /freebsd/share/mk/auto.obj.mk (revision e2afbc45258f2fa4bdcf126e959ac660e76fc802)
1# $Id: auto.obj.mk,v 1.21 2025/08/09 22:42:24 sjg Exp $
2#
3#	@(#) Copyright (c) 2004-2025, Simon J. Gerraty
4#
5#	SPDX-License-Identifier: BSD-2-Clause
6#
7#	Please send copies of changes and bug-fixes to:
8#	sjg@crufty.net
9#
10
11ECHO_TRACE ?= echo
12
13.ifndef Mkdirs
14# A race condition in some versions of mkdir, means that it can bail
15# if another process made a dir that mkdir expected to.
16# We repeat the mkdir -p a number of times to try and work around this.
17# We stop looping as soon as the dir exists.
18# If we get to the end of the loop, a plain mkdir will issue an error.
19Mkdirs= Mkdirs() { \
20	for d in $$*; do \
21		for i in 1 2 3 4 5 6; do \
22			mkdir -p $$d; \
23			test -d $$d && return 0; \
24		done > /dev/null 2>&1; \
25		mkdir $$d || exit $$?; \
26	done; }
27.endif
28
29# if MKOBJDIRS is set to auto (and NOOBJ isn't defined) do some magic...
30# This will automatically create objdirs as needed.
31# Skip it if we are just doing 'clean'.
32.if ${MK_AUTO_OBJ:Uno} == "yes"
33MKOBJDIRS= auto
34.endif
35.if !defined(NOOBJ) && !defined(NO_OBJ) && ${MKOBJDIRS:Uno} == auto
36# Use __objdir here so it is easier to tweak without impacting
37# the logic.
38.if !empty(MAKEOBJDIRPREFIX)
39.if ${.CURDIR:M${MAKEOBJDIRPREFIX}/*} != ""
40# we are already in obj tree!
41__objdir?= ${.CURDIR}
42.endif
43__objdir?= ${MAKEOBJDIRPREFIX}${.CURDIR}
44.endif
45__objdir?= ${MAKEOBJDIR:Uobj}
46# relative dirs can cause trouble below
47# keep it simple and convert to absolute path now if needed
48.if ${__objdir:M/*} == ""
49# avoid ugly ${.CURDIR}/./obj etc.
50__objdir:= ${.CURDIR}/${__objdir:S,^./,,}
51.endif
52.if ${.OBJDIR:tA} != ${__objdir:tA}
53# We need to chdir, make the directory if needed
54.if !exists(${__objdir}/) && \
55	(${.TARGETS} == "" || ${.TARGETS:Nclean*:N*clean:Ndestroy*} != "")
56# This will actually make it...
57__objdir_made != echo ${__objdir}/; umask ${OBJDIR_UMASK:U002}; \
58        ${ECHO_TRACE} "[Creating objdir ${__objdir}...]" >&2; \
59        ${Mkdirs}; Mkdirs ${__objdir}
60.endif
61# This causes make to use the specified directory as .OBJDIR
62.OBJDIR: ${__objdir}
63.if ${.OBJDIR:tA} != ${__objdir:tA}
64# we did not get what we want - do we care?
65.if ${__objdir_made:Uno:M${__objdir}/*} != ""
66# we attempted to make ${__objdir} and failed
67.error could not use ${__objdir}: .OBJDIR=${.OBJDIR}
68.endif
69# apparently we can live with it
70# make sure we know what we have
71.OBJDIR: ${.CURDIR}
72.endif
73.endif
74.endif
75