###############################################################################
# Makefile script for PQoS library and sample application
#
# @par
# BSD LICENSE
#
# Copyright(c) 2014-2026 Intel Corporation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
#   * Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in
#     the documentation and/or other materials provided with the
#     distribution.
#   * Neither the name of Intel Corporation nor the names of its
#     contributors may be used to endorse or promote products derived
#     from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################

include ../pre-build.mk

LIB = libpqos
VERSION = 8.0.0
SO_VERSION = 8
SHARED ?= y
LDFLAGS = -L. -lpthread -z noexecstack -z relro -z now
CFLAGS = -pthread -I./ -D_GNU_SOURCE \
	-W -Wall -Wextra -Wstrict-prototypes -Wmissing-prototypes \
	-Wmissing-declarations -Wold-style-definition -Wpointer-arith \
	-Wcast-qual -Wundef -Wwrite-strings \
	-Wformat -Wformat-security -fstack-protector-strong \
	-Wunreachable-code -Wsign-compare -Wno-endif-labels
ifneq ($(EXTRA_CFLAGS),)
CFLAGS += $(EXTRA_CFLAGS)
endif
ifneq ($(EXTRA_LDFLAGS),)
LDFLAGS += $(EXTRA_LDFLAGS)
endif

DOXY_DIRS = doc_api doc_lib

# ICC and GCC/CLANG options
ifeq ($(CC),icc)
else
# GCC and clang
CFLAGS += -Wcast-align \
    -Wnested-externs \
    -Wmissing-noreturn
endif

IS_GCC = $(shell $(CC) -v 2>&1 | grep -c "^gcc version ")
IS_CLANG = $(shell $(CC) -v 2>&1 | grep -c "^clang version ")

# GCC-only options
ifeq ($(IS_GCC),1)
CFLAGS += -fno-strict-overflow \
    -fno-delete-null-pointer-checks \
    -fwrapv \
    -fstack-clash-protection \
    -fcf-protection=full
endif

# so or static build
ifeq ($(SHARED),y)
CFLAGS += -fPIC
# never unloaded: a thread's exit may be running the resctrl lock's or the API
# lock's key destructor, which deleting the key does not wait for, as another
# thread unloads the library
LDFLAGS += -z nodelete
LIBNAME = $(LIB).so.$(VERSION)
LIBPERM = 0755
else
CFLAGS += -fPIE
LIBNAME = $(LIB).a
LIBPERM = 0644
endif

# DEBUG build
ifeq ($(DEBUG),y)
CFLAGS += -g -ggdb -Og -DDEBUG
else
CFLAGS += -g -O2 -D_FORTIFY_SOURCE=2
endif

# RMID CUSTOM
ifeq ($(RMID_CUSTOM),y)
CFLAGS += -DPQOS_RMID_CUSTOM
endif

# UNLOCK CUSTOM (disable API locking)
ifeq ($(UNLOCK_CUSTOM),y)
CFLAGS += -DUNLOCK_CUSTOM
endif

# The flags above, recorded so that a different SHARED, DEBUG or EXTRA_CFLAGS on
# the command line rebuilds what they compiled: "make SHARED=n" then "make" kept
# the -fPIE objects and failed to link a shared object from them, and "make
# DEBUG=y" after a plain build left ASSERT compiled out. See flags-stamp.mk.
# After the last line that adds to them.
FLAGS_STAMP_DIR = .
include ../flags-stamp.mk

# Build targets and dependencies
SRCS = $(sort $(wildcard *.c))
OBJS = $(SRCS:.c=.o)
CLEAN_OBJS = $(SRCS:.c=.o)

# On FreeBSD build with no OS support
ifeq ($(shell uname), FreeBSD)
OBJS := $(filter-out perf.o \
	os_allocation.o \
	os_cap.o \
	os_monitoring.o \
	os_cpuinfo.o \
	resctrl.o \
	resctrl_alloc.o \
	resctrl_monitoring.o \
	resctrl_schemata.o \
	resctrl_utils.o \
	perf_monitoring.o,$(OBJS))
endif

HDR = pqos.h
PREFIX ?= /usr/local
LIB_INSTALL_DIR ?= $(PREFIX)/lib
HDR_DIR ?= $(PREFIX)/include
DEPFILE = $(LIB).dep
NOLDCONFIG ?= n
# Registers LIB_INSTALL_DIR with the dynamic linker when it is not searched
# by default (e.g. /usr/local/lib on Fedora/RHEL). The file is changed only
# when its first line is LDCONF_MARK, so one written by anyone else is kept.
LDCONF_DIR ?= /etc/ld.so.conf.d
LDCONF_FILE = $(LDCONF_DIR)/$(LIB).conf
LDCONF_MARK = \# Added by $(LIB) make install
LDCONF_OURS = head -n 1 "$(LDCONF_FILE)" 2>/dev/null | \
	grep -qxF '$(LDCONF_MARK)'
# Serialises the read and the rewrite of LDCONF_FILE between installs and
# uninstalls running at once: a lock on LDCONF_DIR, held on descriptor 9 until
# the recipe's shell exits, so one's registration is not lost to the other's
# rewrite of what it read before. A lock that cannot be taken - another
# install holding it past the wait - stops the recipe rather than let the
# write race the other's. Without flock, which a minimal system may lack, the
# recipe says so and goes on without a lock, as every install did before
# there was one. No LDCONF_DIR means nothing to register in and nothing to
# lock.
LDCONF_LOCK = if [ -d "$(LDCONF_DIR)" ]; then \
	if command -v flock >/dev/null; then \
		exec 9<"$(LDCONF_DIR)" && flock -w 30 9 || \
			{ echo "Could not lock $(LDCONF_DIR)" >&2; exit 1; }; \
	else \
		echo "flock not found: no lock against another install or" \
			"uninstall running at once" >&2; \
	fi; fi
# A shell function that writes its arguments, one per line, as the whole of
# LDCONF_FILE: into a file made beside it, 0644 once complete, then renamed
# into place, so the loader's configuration is replaced in one step and never
# seen half written or left truncated by a write that failed. ldconfig reads
# *.conf only, so the file being made is not read by one that runs meanwhile.
LDCONF_WRITE = ldconf_write() { tmp=$$(mktemp "$(LDCONF_FILE).XXXXXX") && \
	{ printf '%s\n' "$$@" > "$$tmp" && chmod 0644 "$$tmp" && \
	  mv -f -- "$$tmp" "$(LDCONF_FILE)" || { rm -f -- "$$tmp"; false; }; }; }
# The cache names a library by the directory ldconfig scanned (/lib64 for
# /usr/lib64 on Fedora), so an entry is matched by file, not by path
LDCACHE_HAS_LIB = ldconfig -p | \
	sed -n 's|.* => \(.*/$(LIB)\.so\.$(SO_VERSION)\)$$|\1|p' | \
	while read -r so; do \
		[ "$$so" -ef "$(LIB_INSTALL_DIR)/$(LIB).so.$(SO_VERSION)" ] && \
			echo "$$so"; \
	done | grep -q .
# LIB_INSTALL_DIR with symbolic links resolved. This is what gets
# registered, so no link above it can later point the loader elsewhere.
LIBDIR_REAL = cd "$(LIB_INSTALL_DIR)" 2>/dev/null && pwd -P
# True when "dir", everything below it and every directory above it are owned
# by root and writable by no one else, and no link below it points out of it;
# otherwise another user could replace what privileged programs load from it,
# and it is not registered. A directory the loader is told to search is
# searched whole, so a file in it another user can write is as good to them as
# the directory; and its subdirectories are searched as well - glibc-
# hwcaps/<subdir> from glibc 2.33 on, and before 2.37 tls, the platform's name
# and hardware capability names in any combination - which ones depending on
# the glibc and the CPU, so the whole tree below is held to the test. The mode
# bits see an ACL too: the mask an ACL carries bounds every right it grants and
# is what the group bits of the mode show, so what another user may write
# through an ACL shows as group-writable. Links are followed, since what the
# loader loads through one is its target: a link's own mode is 0777 and says
# nothing; a dangling link loads nothing and is left out - under -L, -type l is
# true of a dangling link alone. A link's target is taken as written: one that
# is absolute or climbs above "dir" may pass through a path some component of
# which is another user's to repoint, and none of that is looked at here, so it
# is refused; one that stays below "dir", as the library's own links do, passes
# through nothing but what this test covers - as long as no directory on its
# way is itself a link, since a link to "." or to a parent makes a path shorter
# than it reads, so a target that passes through one is refused as well. Each
# link is read by name, one at a time, so a name or a target with a tab or a
# newline in it is read whole. The links are judged first, so that the scan
# that follows them is made only once it is known to stay below "dir". A tree
# that cannot be looked at whole - part of it unreadable, a loop among its
# links, a mount that fails - is refused as well, rather than vouched for on
# what was seen. The first thing found wanting is named.
LIBDIR_TRUSTED = ( d="$$dir"; \
	f=$$(find "$$d" -type l -exec sh -c 'd=$$1; shift; set -f; IFS=/; \
		for l; do t=$$(readlink -- "$$l") || exit 2; \
			case $$t in /*) echo "$$l out"; exit 0;; esac; \
			p=$${l%/*}; p=$${p\#"$$d"}/$$t; k=0; cur=$$d; \
			n=$$(set -- $$p; echo $$\#); i=0; \
			for c in $$p; do i=$$((i + 1)); case $$c in \
				""|.) ;; \
				..) k=$$((k - 1)); [ $$k -ge 0 ] || { echo "$$l out"; exit 0; }; \
					cur=$${cur%/*};; \
				*) k=$$((k + 1)); cur=$$cur/$$c; [ $$i -eq $$n ] || \
					[ ! -L "$$cur" ] || { echo "$$l via"; exit 0; };; \
			esac; done; \
		done' sh "$$d" {} + 2>/dev/null) || \
		{ echo "not all of $$d could be examined"; exit 1; }; \
	case $$f in \
		"") ;; \
		*" via") echo "$${f% via} is a link whose target passes through" \
			"another link"; exit 1;; \
		*) echo "$${f% out} is a link pointing out of $$dir"; exit 1;; \
	esac; \
	f=$$(find -L "$$d" ! -type l \( ! -user 0 -o -perm /022 \) \
		-print -quit 2>/dev/null) || \
		{ echo "not all of $$d could be examined"; exit 1; }; \
	[ -z "$$f" ] || \
		{ echo "$$f is not owned by root or is writable by others"; exit 1; }; \
	while [ -n "$$(find "$$d" -maxdepth 0 -user 0 ! -perm /022)" ]; do \
		[ "$$d" = / ] && exit 0; \
		d=$$(dirname "$$d"); \
	done; echo "$$d is not owned by root or is writable by others"; exit 1 )

all: unselected-form

# the stamp as well, for the flags only the link reads (EXTRA_LDFLAGS), and kept
# off the link line, which takes the objects alone
$(LIBNAME): $(OBJS) $(FLAGS_STAMP)
ifeq ($(SHARED),y)
	$(CC) $(LDFLAGS) -shared -Wl,-soname,$(LIB).so.$(SO_VERSION) -o $(LIBNAME) $(filter %.o,$^) -lc
	ln -f -s $(LIBNAME) $(LIB).so.$(SO_VERSION)
	ln -f -s $(LIB).so.$(SO_VERSION) $(LIB).so
else
	$(AR) crvsD $@ $(filter %.o,$^)
endif

# The form that was not built goes once this one is there. Consumers link with
# -lpqos, and the linker prefers a .so where both are there, so a "make
# SHARED=n" that left the shared library from an earlier build in place had
# every consumer link that one instead of the archive just built. Phony, so it
# runs on every build and not only one that relinks - a library already up to
# date still has the other form beside it. After the library and not before
# it, so that a build which fails leaves what was working where it was.
.PHONY: unselected-form
unselected-form: $(LIBNAME)
ifeq ($(SHARED),y)
	rm -f $(LIB).a
else
	rm -f $(LIB).so $(LIB).so.$(SO_VERSION) $(LIB).so.$(VERSION)
endif

install: unselected-form

# Install on FreeBSD
ifeq ($(shell uname), FreeBSD)
	install -d $(LIB_INSTALL_DIR)
	install -m $(LIBPERM) $(LIBNAME) $(LIB_INSTALL_DIR)
	install -m 0644 $(HDR) $(HDR_DIR)
# Install on Linux
else
	install -m $(LIBPERM) $(LIBNAME) -D $(LIB_INSTALL_DIR)/$(LIBNAME)
	install -m 0644 $(HDR) -D $(HDR_DIR)/$(HDR)
endif

# Create symlinks to DSO
ifeq ($(SHARED),y)
	cd $(LIB_INSTALL_DIR); \
		ln -f -s $(LIB).so.$(VERSION) $(LIB).so.$(SO_VERSION); \
		ln -f -s $(LIB).so.$(SO_VERSION) $(LIB).so
ifneq ($(NOLDCONFIG),y)
ifeq ($(shell uname), FreeBSD)
	ldconfig
else
# ldconfig under the lock as well: two running at once clash on the cache's
# temporary name and one of them fails, which ended that install before it
# registered its directory. The library is looked for again once the lock is
# held: an uninstall of the same prefix running at the same time removes it
# before its own turn under the lock, and its sweep keeps no line for a
# directory with no library in it, so none is made for one either
	@$(LDCONF_LOCK); $(LDCONF_WRITE); ldconfig || exit 1; \
	dir=$$($(LIBDIR_REAL)); \
	[ -f "$$dir/$(LIBNAME)" ] || { echo "$(LIB_INSTALL_DIR)/$(LIBNAME)" \
		"was removed before it could be registered" >&2; exit 1; }; \
	cached=n; $(LDCACHE_HAS_LIB) && cached=y; \
	if [ $$cached = n ] && [ -d "$(LDCONF_DIR)" ]; then \
		if ! why=$$( $(LIBDIR_TRUSTED) ); then \
			echo "Not adding $$dir to the dynamic linker search" \
				"path: $$why"; \
			hint="set LD_LIBRARY_PATH, or install below a directory" \
			hint="$$hint owned by root and writable by no one else"; \
		else \
			[ -e "$(LDCONF_FILE)" ] || [ -L "$(LDCONF_FILE)" ] || \
				ldconf_write '$(LDCONF_MARK)'; \
			if [ ! -e "$(LDCONF_FILE)" ] && [ ! -L "$(LDCONF_FILE)" ]; then \
				echo "Could not create $(LDCONF_FILE)" >&2; exit 1; \
			elif ! $(LDCONF_OURS); then \
				echo "$(LDCONF_FILE) was not written by $(LIB)" \
					"make install, leaving it unchanged"; \
			elif ! grep -qxF -- "$$dir" "$(LDCONF_FILE)"; then \
				echo "Adding $$dir to the dynamic linker" \
					"search path in $(LDCONF_FILE)"; \
				keep=$$(tail -n +2 "$(LDCONF_FILE)") || exit 1; \
				ldconf_write '$(LDCONF_MARK)' $${keep:+"$$keep"} \
					"$$dir" && ldconfig || exit 1; \
				$(LDCACHE_HAS_LIB) && cached=y; \
			fi; \
		fi; \
	fi; \
	[ $$cached = y ] || echo "WARNING: $(LIB_INSTALL_DIR) is not in" \
		"the dynamic linker search path:" \
		"$${hint:-add it to a file in $(LDCONF_DIR) or to LD_LIBRARY_PATH}"
endif
endif
endif

uninstall:
	-rm $(LIB_INSTALL_DIR)/libpqos*
# on Linux whatever SHARED is: the rm above took the shared library too, if
# it was there, so the loader's configuration and cache are brought up to date
ifneq ($(NOLDCONFIG),y)
ifeq ($(shell uname), FreeBSD)
ifeq ($(SHARED),y)
	ldconfig
endif
else
# Every line of ours names a directory install put the library in, so one whose
# directory holds no libpqos shared object of any version any more, anywhere
# below it - the loader searches a directory's hwcaps subdirectories as well -
# is stale and goes: this uninstall's own directory, just emptied above, and
# any emptied or removed since it was registered - under whatever name, or
# through whatever link, it is reached by today. A line whose library is still
# there stays, which is what a prefix that still holds an install needs; of any
# version, so that a library of another SONAME installed there by another
# release of this file keeps its line, and a regular file that is there, or a
# link that resolves to one, not a link left dangling by one removed. The tree
# is walked as it lies on disk, no link to a directory followed: nothing vets
# the tree again here, and a link added since the install could lead anywhere.
# A directory that cannot be seen at the time, on a filesystem not mounted,
# reads as empty and goes too; the next install there puts it back.
	@$(LDCONF_LOCK); $(LDCONF_WRITE); if $(LDCONF_OURS); then \
		lines=$$(tail -n +2 "$(LDCONF_FILE)") || exit 1; \
		keep=$$(printf '%s\n' "$$lines" | while IFS= read -r d; do \
			[ -n "$$d" ] || continue; \
			if find "$$d" -name '$(LIB).so.[0-9]*' \( -type f -o -type l \) \
				-exec test -f {} \; -print -quit 2>/dev/null | grep -q .; then \
				printf '%s\n' "$$d"; \
			else \
				echo "Removing $$d from $(LDCONF_FILE)" >&2; \
			fi; \
		done); \
		if [ -z "$$keep" ]; then \
			rm -f -- "$(LDCONF_FILE)" || exit 1; \
		else \
			ldconf_write '$(LDCONF_MARK)' "$$keep" || exit 1; \
		fi; \
	fi; \
	ldconfig
endif
endif

DEPFILES = $(SRCS:.c=.d)

# what an object is made of besides its source: the flags it was compiled with,
# and the file that says which they are
$(OBJS) $(DEPFILES): Makefile $(FLAGS_STAMP)

%.o: %.c %.d

%.d: %.c
	set -e; rm -f $@; \
	$(CC) -MM -MP -MF $@ $(CFLAGS) $< > $@.$$$$; \
	sed 's/$(@:.d=.o)/$@/' < $@.$$$$ > $@; \
	rm -f $@.$$$$

.PHONY: clean clobber doxy help

help:
	@echo "PQoS library make targets:"
	@echo "    make              - build shared library"
	@echo "    make SHARED=n     - build static library"
	@echo "    make DEBUG=y      - build shared library for debugging"
	@echo "    make install      - install library (accepts PREFIX=/some/where)"
	@echo "    make uninstall    - uninstall library (accepts PREFIX=/some/where)"
	@echo "    make clean        - remove files produced normally by make"
	@echo "    make clobber      - clean and remove documentation"
	@echo "    make doxy         - make doxygen documentation"
	@echo "    make style        - coding style check (accepts CHECKPATCH=/some/where/checkpatch.pl)"
	@echo "    make cppcheck     - static code analysis (accepts CPPCHECK=/some/where/cppcheck)"

doxy:
	doxygen api_doxygen.cfg
	doxygen lib_doxygen.cfg

# The flags stamp goes with a clean when nothing in the same invocation builds.
# A later build then records the options it compiles with, and an install -
# which reads the stamp and does not write it - builds the missing objects and
# makes the stamp for them. Left in place, it said what the objects before the
# clean were built with: after "make DEBUG=y", "make clean" and "make install",
# the next "make DEBUG=y" found it current and kept the install's release
# objects. A goal that builds, as in "make clean all", wrote the stamp for its
# own options while the Makefile was read, before clean ran, and make does not
# look at it again, so there clean leaves it.
ifeq ($(filter-out $(FLAGS_STAMP_READERS),$(MAKECMDGOALS)),)
CLEAN_FLAGS_STAMP = $(FLAGS_STAMP)
endif

clean:
	-rm -f $(CLEAN_OBJS) $(LIB)* $(DEPFILES) $(CLEAN_FLAGS_STAMP)

clobber:
	-rm -f $(CLEAN_OBJS) $(LIB)* $(DEPFILES) $(CLEAN_FLAGS_STAMP)
	-rm -rf $(DOXY_DIRS)

CHECKPATCH?=checkpatch.pl
.PHONY: checkpatch
checkpatch:
	$(CHECKPATCH) --no-tree --no-signoff --emacs \
	--ignore $(CHECKPATCH_IGNORE) \
	--typedefsfile ../.checkpatch.types \
	--file *.[ch]

CLANGFORMAT?=clang-format
.PHONY: clang-format
clang-format:
	@for file in $(wildcard *.[ch]); do \
		echo "Checking style $$file"; \
		$(CLANGFORMAT) -style=file "$$file" | diff "$$file" - | tee /dev/stderr | [ $$(wc -c) -eq 0 ] || \
		{ echo "ERROR: $$file has style problems"; exit 1; } \
	done

CODESPELL?=codespell
.PHONY: codespell
codespell:
	$(CODESPELL) . -q 2 -L clos,mmapped,uint,te,circularly

.PHONY: style
style:
	$(MAKE) checkpatch
	$(MAKE) clang-format
	$(MAKE) codespell

CPPCHECK?=cppcheck
.PHONY: cppcheck
cppcheck:
	$(CPPCHECK) \
	--enable=warning,portability,performance,missingInclude \
	--std=c99 --template=gcc \
	--suppress=missingIncludeSystem \
	api.c api.h cap.c cap.h common.h common.c allocation.c perf.c perf.h \
	allocation.h allocation_common.c allocation_common.h monitoring.c monitoring.h \
	log.c log.h types.h machine.c machine.h \
	utils.c utils.h \
	cpuinfo.c cpuinfo.h os_allocation.h os_allocation.c \
	hw_cap.h hw_cap.c \
	hybrid.h hybrid.c \
	hw_monitoring.h hw_monitoring.c \
	lock.h lock.c \
	os_cap.h os_cap.c \
	os_common.h \
	os_monitoring.h os_monitoring.c \
	perf_monitoring.h perf_monitoring.c \
	resctrl_alloc.h resctrl_alloc.c \
	resctrl.h resctrl.c \
	resctrl_monitoring.h resctrl_monitoring.c \
	resctrl_schemata.h resctrl_schemata.c \
	resctrl_utils.h resctrl_utils.c \
	acpi.h acpi.c acpi_table.h \
	iordt.h iordt.c \
	uncore_monitoring.h uncore_monitoring.c

# if target not clean or rinse then make dependencies
ifneq ($(MAKECMDGOALS),clean)
ifneq ($(MAKECMDGOALS),clobber)
ifneq ($(MAKECMDGOALS),style)
ifneq ($(MAKECMDGOALS),clang-format)
ifneq ($(MAKECMDGOALS),checkpatch)
ifneq ($(MAKECMDGOALS),codespell)
-include $(DEPFILES)
endif
endif
endif
endif
endif
endif
