doc/SHA256SUMS: Add the list of SHA-256 hashes of release files
[xz.git] / CMakeLists.txt
blobf47eb36985f5d472a783abad5c4ffc843243d4b3
1 # SPDX-License-Identifier: 0BSD
3 #############################################################################
5 # CMake support for building XZ Utils
7 # Requirements:
9 #   - CMake 3.20 or later
11 #   - To get translated messages, install GNU gettext tools (the command
12 #     msgfmt is needed). Alternatively disable translations by setting
13 #     XZ_NLS=OFF.
15 #   - If building from xz.git instead of a release tarball: To generate
16 #     translated man pages, run po4a/update-po which requires the po4a
17 #     tool. The build works without this step too.
19 # About CMAKE_BUILD_TYPE:
21 #   - CMake's standard choices are fine to use for production builds,
22 #     including "Release" and "RelWithDebInfo".
24 #     NOTE: While "Release" uses -O3 by default with some compilers,
25 #     this file overrides -O3 to -O2 for "Release" builds if
26 #     CMAKE_C_FLAGS_RELEASE is not defined by the user. At least
27 #     with GCC and Clang/LLVM, -O3 doesn't seem useful for this
28 #     package as it can result in bigger binaries without any
29 #     improvement in speed compared to -O2.
31 #   - Empty value (the default) is handled slightly specially: It
32 #     adds -DNDEBUG to disable debugging code (assert() and a few
33 #     other things). No optimization flags are added so an empty
34 #     CMAKE_BUILD_TYPE is an easy way to build with whatever
35 #     optimization flags one wants, and so this method is also
36 #     suitable for production builds.
38 #     If debugging is wanted when using empty CMAKE_BUILD_TYPE,
39 #     include -UNDEBUG in the CFLAGS environment variable or
40 #     in the CMAKE_C_FLAGS CMake variable to override -DNDEBUG.
41 #     With empty CMAKE_BUILD_TYPE, the -UNDEBUG option will go
42 #     after the -DNDEBUG option on the compiler command line and
43 #     thus NDEBUG will be undefined.
45 #   - Non-standard build types like "None" aren't treated specially
46 #     and thus won't have -DNEBUG. Such non-standard build types
47 #     SHOULD BE AVOIDED FOR PRODUCTION BUILDS. Or at least one
48 #     should remember to add -DNDEBUG.
50 # This file provides the following installation components (if you only
51 # need liblzma, install only its components!):
52 #   - liblzma_Runtime (shared library only)
53 #   - liblzma_Development
54 #   - liblzma_Documentation (examples and Doxygen-generated API docs as HTML)
55 #   - xz_Runtime (xz, the symlinks, and possibly translation files)
56 #   - xz_Documentation (xz man pages and the symlinks)
57 #   - xzdec_Runtime
58 #   - xzdec_Documentation (xzdec *and* lzmadec man pages)
59 #   - lzmadec_Runtime
60 #   - lzmainfo_Runtime
61 #   - lzmainfo_Documentation (lzmainfo man pages)
62 #   - scripts_Runtime (xzdiff, xzgrep, xzless, xzmore)
63 #   - scripts_Documentation (their man pages)
64 #   - Documentation (generic docs like README and licenses)
66 # To find the target liblzma::liblzma from other packages, use the CONFIG
67 # option with find_package() to avoid a conflict with the FindLibLZMA module
68 # with case-insensitive file systems. For example, to require liblzma 5.2.5
69 # or a newer compatible version:
71 #     find_package(liblzma 5.2.5 REQUIRED CONFIG)
72 #     target_link_libraries(my_application liblzma::liblzma)
74 #############################################################################
76 # Author: Lasse Collin
78 #############################################################################
80 cmake_minimum_required(VERSION 3.20...3.30 FATAL_ERROR)
82 include(CMakePushCheckState)
83 include(CheckIncludeFile)
84 include(CheckSymbolExists)
85 include(CheckStructHasMember)
86 include(CheckCSourceCompiles)
87 include(CheckCCompilerFlag)
88 include(cmake/tuklib_large_file_support.cmake)
89 include(cmake/tuklib_integer.cmake)
90 include(cmake/tuklib_cpucores.cmake)
91 include(cmake/tuklib_physmem.cmake)
92 include(cmake/tuklib_progname.cmake)
93 include(cmake/tuklib_mbstr.cmake)
95 set(PACKAGE_NAME "XZ Utils")
96 set(PACKAGE_BUGREPORT "xz@tukaani.org")
97 set(PACKAGE_URL "https://tukaani.org/xz/")
99 # Get the package version from version.h into PACKAGE_VERSION_SHORT and
100 # PACKAGE_VERSION. The former variable won't include the possible "alpha"
101 # or "beta" suffix.
102 file(READ src/liblzma/api/lzma/version.h PACKAGE_VERSION)
103 string(REGEX REPLACE
104 "^.*\n\
105 #define LZMA_VERSION_MAJOR ([0-9]+)\n\
107 #define LZMA_VERSION_MINOR ([0-9]+)\n\
109 #define LZMA_VERSION_PATCH ([0-9]+)\n\
110 .*$"
111        "\\1.\\2.\\3" PACKAGE_VERSION_SHORT "${PACKAGE_VERSION}")
113 if(PACKAGE_VERSION MATCHES "\n#define [A-Z_ ]*_ALPHA\n")
114     set(PACKAGE_VERSION "${PACKAGE_VERSION_SHORT}alpha")
115 elseif(PACKAGE_VERSION MATCHES "\n#define [A-Z_ ]*_BETA\n")
116     set(PACKAGE_VERSION "${PACKAGE_VERSION_SHORT}beta")
117 else()
118     set(PACKAGE_VERSION "${PACKAGE_VERSION_SHORT}")
119 endif()
121 # With several compilers, CMAKE_BUILD_TYPE=Release uses -O3 optimization
122 # which results in bigger code without a clear difference in speed. If
123 # no user-defined CMAKE_C_FLAGS_RELEASE is present, override -O3 to -O2
124 # to make it possible to recommend CMAKE_BUILD_TYPE=Release.
125 if(NOT DEFINED CMAKE_C_FLAGS_RELEASE)
126     set(OVERRIDE_O3_IN_C_FLAGS_RELEASE ON)
127 endif()
129 # Among other things, this gives us variables xz_VERSION and xz_VERSION_MAJOR.
130 project(xz VERSION "${PACKAGE_VERSION_SHORT}" LANGUAGES C)
132 if(OVERRIDE_O3_IN_C_FLAGS_RELEASE)
133     # Looking at CMake's source, there aren't any _FLAGS_RELEASE_INIT
134     # entries where "-O3" would appear as part of some other option,
135     # thus a simple search and replace should be fine.
136     string(REPLACE -O3 -O2 CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}")
138     # Update the cache value while keeping its docstring unchanged.
139     set_property(CACHE CMAKE_C_FLAGS_RELEASE
140                  PROPERTY VALUE "${CMAKE_C_FLAGS_RELEASE}")
141 endif()
143 # Reject unsupported MSVC versions.
144 if(MSVC AND MSVC_VERSION LESS 1900)
145     message(FATAL_ERROR "Visual Studio older than 2015 is not supported")
146 endif()
148 # We need a compiler that supports enough C99 or newer (variable-length arrays
149 # aren't needed, those are optional in C11/C17). C11 is preferred since C11
150 # features may be optionally used if they are available.
152 # Setting CMAKE_C_STANDARD here makes it the default for all targets.
153 # It doesn't affect the INTERFACE so liblzma::liblzma won't end up with
154 # INTERFACE_COMPILE_FEATURES "c_std_99" or such (the API headers are C89
155 # and C++ compatible).
157 # Avoid set(CMAKE_C_STANDARD_REQUIRED ON) because it's fine to decay
158 # to C99 if C11 isn't supported.
159 set(CMAKE_C_STANDARD 11)
161 # On Apple OSes, don't build executables as bundles:
162 set(CMAKE_MACOSX_BUNDLE OFF)
164 # Set CMAKE_INSTALL_LIBDIR and friends. This needs to be done before
165 # the LOCALEDIR_DEFINITION workaround below.
166 include(GNUInstallDirs)
168 # windres from GNU binutils can be tricky with command line arguments
169 # that contain spaces or other funny characters. Unfortunately we need
170 # a space in PACKAGE_NAME. Using \x20 to encode the US-ASCII space seems
171 # to work in both cmd.exe and /bin/sh.
173 # However, even \x20 isn't enough in all situations, resulting in
174 # "syntax error" from windres. Using --use-temp-file prevents windres
175 # from using popen() and this seems to fix the problem.
177 # llvm-windres from Clang/LLVM 16.0.6 and older: The \x20 results
178 # in "XZx20Utils" in the compiled binary. The option --use-temp-file
179 # makes no difference.
181 # llvm-windres 17.0.0 and later: It emulates GNU windres more accurately, so
182 # the workarounds used with GNU windres must be used with llvm-windres too.
184 # CMake 3.27 doesn't have CMAKE_RC_COMPILER_ID so we rely on
185 # CMAKE_C_COMPILER_ID.
186 if((MINGW OR CYGWIN) AND (
187         NOT CMAKE_C_COMPILER_ID STREQUAL "Clang" OR
188         CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL "17"))
189     # Use workarounds with GNU windres and llvm-windres >= 17.0.0. The \x20
190     # in PACKAGE_NAME_DEFINITION works with gcc and clang too so we don't need
191     # to worry how to pass different flags to windres and the C compiler.
192     # Keep the original PACKAGE_NAME intact for generation of liblzma.pc.
193     string(APPEND CMAKE_RC_FLAGS " --use-temp-file")
194     string(REPLACE " " "\\040" PACKAGE_NAME_DEFINITION "${PACKAGE_NAME}")
196     # Use octal because "Program Files" would become \x20F.
197     string(REPLACE " " "\\040" LOCALEDIR_DEFINITION
198            "${CMAKE_INSTALL_FULL_LOCALEDIR}")
199 else()
200     # Elsewhere a space is safe. This also keeps things compatible with
201     # EBCDIC in case CMake-based build is ever done on such a system.
202     set(PACKAGE_NAME_DEFINITION "${PACKAGE_NAME}")
203     set(LOCALEDIR_DEFINITION "${CMAKE_INSTALL_FULL_LOCALEDIR}")
204 endif()
206 # When used with MSVC, CMake can merge .manifest files with
207 # linker-generated manifests and embed the result in an executable.
208 # However, when paired with MinGW-w64, CMake (3.30) ignores .manifest
209 # files. Embedding a manifest with a resource file works with both
210 # toochains. It's also the way to do it with Autotools.
212 # With MSVC, we need to disable the default manifest; attempting to add
213 # two manifest entries would break the build. The flag /MANIFEST:NO
214 # goes to the linker and it also affects behavior of CMake itself: it
215 # looks what flags are being passed to the linker and when CMake sees
216 # the /MANIFEST:NO option, other manifest-related linker flags are
217 # no longer added (see the file Source/cmcmd.cxx in CMake).
219 # See: https://gitlab.kitware.com/cmake/cmake/-/issues/23066
220 if(MSVC)
221     set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /MANIFEST:NO")
222 endif()
224 # Dependencies for all Windows resource files:
225 set(W32RES_DEPENDENCIES
226     "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
227     "${CMAKE_CURRENT_SOURCE_DIR}/src/common/w32_application.manifest"
230 # Definitions common to all targets:
231 add_compile_definitions(
232     # Package info:
233     PACKAGE_NAME="${PACKAGE_NAME_DEFINITION}"
234     PACKAGE_BUGREPORT="${PACKAGE_BUGREPORT}"
235     PACKAGE_URL="${PACKAGE_URL}"
237     # Standard headers and types are available:
238     HAVE_STDBOOL_H
239     HAVE__BOOL
240     HAVE_STDINT_H
241     HAVE_INTTYPES_H
243     # Always enable CRC32 since liblzma should never build without it.
244     HAVE_CHECK_CRC32
246     # Disable assert() checks when no build type has been specified. Non-empty
247     # build types like "Release" and "Debug" handle this by default.
248     $<$<CONFIG:>:NDEBUG>
251 # Support 32-bit x86 assembly files.
252 if(NOT MSVC)
253     # It's simplest to ask the compiler for the architecture because we
254     # know that on supported platforms __i386__ is defined.
255     #
256     # Checking CMAKE_SYSTEM_PROCESSOR wouldn't be so simple or as reliable
257     # because it could indicate x86-64 even if building for 32-bit x86
258     # because one doesn't necessarily use a CMake toolchain file when
259     # building 32-bit executables on a 64-bit system. Also, the strings
260     # that identify 32-bit or 64-bit x86 aren't standardized in CMake.
261     if(MINGW OR CYGWIN OR CMAKE_SYSTEM_NAME MATCHES
262             "^FreeBSD$|^GNU$|^Linux$|^MirBSD$|^NetBSD$|^OpenBSD$")
263         check_symbol_exists("__i386__" "" ASM_I386_DEFAULT)
264     else()
265         set(ASM_I386_DEFAULT OFF)
266     endif()
268     option(XZ_ASM_I386 "Enable 32-bit x86 assembly code"
269            "${ASM_I386_DEFAULT}")
271     if(XZ_ASM_I386)
272         enable_language(ASM)
273     endif()
274 endif()
277 ######################
278 # System definitions #
279 ######################
281 # _GNU_SOURCE and such definitions. This specific macro is special since
282 # it also adds the definitions to CMAKE_REQUIRED_DEFINITIONS.
283 tuklib_use_system_extensions(ALL)
285 # Check for large file support. It's required on some 32-bit platforms and
286 # even on 64-bit MinGW-w64 to get 64-bit off_t. This can be forced off on
287 # the CMake command line if needed: -DLARGE_FILE_SUPPORT=OFF
288 tuklib_large_file_support(ALL)
290 # This is needed by liblzma and xz.
291 tuklib_integer(ALL)
293 # This is used for liblzma.pc generation to add -lrt and -lmd if needed.
295 # The variable name LIBS comes from Autoconf where AC_SEARCH_LIBS adds the
296 # libraries it finds into the shell variable LIBS. These libraries need to
297 # be put into liblzma.pc too, thus liblzma.pc.in has @LIBS@ because that
298 # matches the Autoconf's variable. When CMake support was added, using
299 # the same variable with configure_file() was the simplest method.
300 set(LIBS)
302 # Check for clock_gettime(). Do this before checking for threading so
303 # that we know there if CLOCK_MONOTONIC is available.
304 check_symbol_exists(clock_gettime time.h HAVE_CLOCK_GETTIME)
306 if(NOT HAVE_CLOCK_GETTIME)
307     # With glibc <= 2.17 or Solaris 10 this needs librt.
308     # Add librt for the next check for HAVE_CLOCK_GETTIME. If it is
309     # found after including the library, we know that librt is required.
310     list(PREPEND CMAKE_REQUIRED_LIBRARIES rt)
311     check_symbol_exists(clock_gettime time.h HAVE_CLOCK_GETTIME_LIBRT)
313     # If it was found now, add librt to all targets and keep it in
314     # CMAKE_REQUIRED_LIBRARIES for further tests too.
315     if(HAVE_CLOCK_GETTIME_LIBRT)
316         link_libraries(rt)
317         set(LIBS "-lrt ${LIBS}") # For liblzma.pc
318     else()
319         list(POP_FRONT CMAKE_REQUIRED_LIBRARIES)
320     endif()
321 endif()
323 if(HAVE_CLOCK_GETTIME OR HAVE_CLOCK_GETTIME_LIBRT)
324     add_compile_definitions(HAVE_CLOCK_GETTIME)
326     # Check if CLOCK_MONOTONIC is available for clock_gettime().
327     check_symbol_exists(CLOCK_MONOTONIC time.h HAVE_CLOCK_MONOTONIC)
328     tuklib_add_definition_if(ALL HAVE_CLOCK_MONOTONIC)
329 endif()
332 # The definition ENABLE_NLS is added only to those targets that use it, thus
333 # it's not done here. (xz has translations, xzdec doesn't.)
334 set(XZ_NLS_DEFAULT OFF)
335 find_package(Intl)
336 find_package(Gettext)
337 if(Intl_FOUND AND GETTEXT_FOUND)
338     set(XZ_NLS_DEFAULT ON)
339 endif()
341 option(XZ_NLS "Native Language Support (translated messages and man pages)"
342        "${XZ_NLS_DEFAULT}")
344 if(XZ_NLS)
345     if(NOT Intl_FOUND)
346         message(FATAL_ERROR "Native language support (NLS) was enabled but "
347                             "find_package(Intl) failed. "
348                             "Install libintl or set XZ_NLS=OFF.")
349     endif()
351     if(NOT GETTEXT_FOUND)
352         message(FATAL_ERROR "Native language support (NLS) was enabled but "
353                             "find_package(Gettext) failed. "
354                             "Install gettext tools or set XZ_NLS=OFF.")
355     endif()
357     # Warn if translated man pages are missing.
358     if(UNIX AND NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/po4a/man")
359         message(WARNING "Native language support (NLS) was enabled "
360                         "but pre-generated translated man pages "
361                         "were not found and thus they won't be installed. "
362                         "Run 'po4a/update-po' to generate them.")
363     endif()
365     # The *installed* name of the translation files is "xz.mo".
366     set(TRANSLATION_DOMAIN "xz")
367 endif()
370 # Add warning options for GCC or Clang. Keep this in sync with configure.ac.
372 # NOTE: add_compile_options() doesn't affect the feature checks;
373 # only the new targets being created use these flags. Thus
374 # the -Werror usage in checks won't be break because of these.
375 if(CMAKE_C_COMPILER_ID MATCHES GNU|Clang)
376     foreach(OPT -Wall
377                 -Wextra
378                 -Wvla
379                 -Wformat=2
380                 -Winit-self
381                 -Wmissing-include-dirs
382                 -Wshift-overflow=2
383                 -Wstrict-overflow=3
384                 -Walloc-zero
385                 -Wduplicated-cond
386                 -Wfloat-equal
387                 -Wundef
388                 -Wshadow
389                 -Wpointer-arith
390                 -Wbad-function-cast
391                 -Wwrite-strings
392                 -Wdate-time
393                 -Wsign-conversion
394                 -Wfloat-conversion
395                 -Wlogical-op
396                 -Waggregate-return
397                 -Wstrict-prototypes
398                 -Wold-style-definition
399                 -Wmissing-prototypes
400                 -Wmissing-declarations
401                 -Wredundant-decls
403                 -Wc99-compat
404                 -Wc11-extensions
405                 -Wc2x-compat
406                 -Wc2x-extensions
407                 -Wpre-c2x-compat
408                 -Warray-bounds-pointer-arithmetic
409                 -Wassign-enum
410                 -Wconditional-uninitialized
411                 -Wdocumentation
412                 -Wduplicate-enum
413                 -Wempty-translation-unit
414                 -Wflexible-array-extensions
415                 -Wmissing-variable-declarations
416                 -Wnewline-eof
417                 -Wshift-sign-overflow
418                 -Wstring-conversion
419                 )
420         # A variable name cannot have = in it so replace = with _.
421         string(REPLACE = _ CACHE_VAR "HAVE_COMPILER_OPTION_${OPT}")
423         check_c_compiler_flag("${OPT}" "${CACHE_VAR}")
425         if("${${CACHE_VAR}}")
426             add_compile_options("${OPT}")
427         endif()
428     endforeach()
429 endif()
432 #############################################################################
433 # liblzma
434 #############################################################################
436 option(BUILD_SHARED_LIBS "Build liblzma as a shared library instead of static")
438 # Symbol versioning is supported with ELF shared libraries on certain OSes.
439 # First assume that symbol versioning isn't supported.
440 set(SYMBOL_VERSIONING "no")
442 if(NOT WIN32)
443     # The XZ_SYMBOL_VERSIONING option is ignored for static libraries but
444     # we keep the option visible still in case the project is reconfigured
445     # to build a shared library.
446     #
447     # auto      Autodetect between no, generic, and linux
448     # yes       Force on by autodetecting between linux and generic
449     # no        Disable symbol versioning
450     # generic   FreeBSD, most Linux/glibc systems, and GNU/Hurd
451     # linux     Linux/glibc with extra symbol versions for compatibility
452     #           with binaries that have been linked against a liblzma version
453     #           that has been patched with "xz-5.2.2-compat-libs.patch" from
454     #           RHEL/CentOS 7.
455     set(SUPPORTED_SYMBOL_VERSIONING_VARIANTS auto yes no generic linux)
456     set(XZ_SYMBOL_VERSIONING "auto" CACHE STRING "Enable ELF shared library \
457 symbol versioning (${SUPPORTED_SYMBOL_VERSIONING_VARIANTS})")
459     # Show a dropdown menu in CMake GUI:
460     set_property(CACHE XZ_SYMBOL_VERSIONING
461                  PROPERTY STRINGS "${SUPPORTED_SYMBOL_VERSIONING_VARIANTS}")
463     if(NOT XZ_SYMBOL_VERSIONING IN_LIST SUPPORTED_SYMBOL_VERSIONING_VARIANTS)
464         message(FATAL_ERROR "'${XZ_SYMBOL_VERSIONING}' is not a supported "
465                             "symbol versioning variant")
466     endif()
468     if(NOT XZ_SYMBOL_VERSIONING MATCHES "^auto$|^yes$")
469         # Autodetection was disabled. Use the user-specified value as is.
470         set(SYMBOL_VERSIONING "${XZ_SYMBOL_VERSIONING}")
471     else()
472         # Autodetect the symbol versioning variant.
473         #
474         # Avoid symvers on Linux with non-glibc like musl and uClibc.
475         # In Autoconf it's enough to check that $host_os equals linux-gnu
476         # instead of, for example, linux-musl. CMake doesn't provide such
477         # a method.
478         #
479         # This check is here for now since it's not strictly required
480         # by anything else.
481         if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
482             check_c_source_compiles(
483                     "#include <features.h>
484                     #if defined(__GLIBC__) && !defined(__UCLIBC__)
485                     int main(void) { return 0; }
486                     #else
487                     compile error
488                     #endif
489                 "
490                 IS_LINUX_WITH_GLIBC)
491         else()
492             set(IS_LINUX_WITH_GLIBC OFF)
493         endif()
495         if(IS_LINUX_WITH_GLIBC AND
496                 (CMAKE_SYSTEM_PROCESSOR MATCHES "[Mm]icro[Bb]laze" OR
497                  CMAKE_C_COMPILER_ID STREQUAL "NVHPC"))
498             # As a special case, GNU/Linux on MicroBlaze gets the generic
499             # symbol versioning because GCC 12 doesn't support the __symver__
500             # attribute on MicroBlaze. On Linux, CMAKE_SYSTEM_PROCESSOR comes
501             # from "uname -m" for native builds (should be "microblaze") or
502             # from the CMake toolchain file (not perfectly standardized but
503             # it very likely has "microblaze" in lower case or mixed case
504             # somewhere in the string).
505             #
506             # NVIDIA HPC Compiler doesn't support symbol versioning but
507             # it uses the linked from the system so the linker script
508             # can still be used to get the generic symbol versioning.
509             set(SYMBOL_VERSIONING "generic")
511         elseif(IS_LINUX_WITH_GLIBC)
512             # GNU/Linux-specific symbol versioning for shared liblzma. This
513             # includes a few extra compatibility symbols for RHEL/CentOS 7
514             # which are pointless on non-glibc non-Linux systems.
515             set(SYMBOL_VERSIONING "linux")
517         elseif(CMAKE_SYSTEM_NAME MATCHES "^FreeBSD$|^GNU$" OR
518                XZ_SYMBOL_VERSIONING STREQUAL "yes")
519             set(SYMBOL_VERSIONING "generic")
520         endif()
521     endif()
522 endif()
524 set(LIBLZMA_API_HEADERS
525     src/liblzma/api/lzma.h
526     src/liblzma/api/lzma/base.h
527     src/liblzma/api/lzma/bcj.h
528     src/liblzma/api/lzma/block.h
529     src/liblzma/api/lzma/check.h
530     src/liblzma/api/lzma/container.h
531     src/liblzma/api/lzma/delta.h
532     src/liblzma/api/lzma/filter.h
533     src/liblzma/api/lzma/hardware.h
534     src/liblzma/api/lzma/index.h
535     src/liblzma/api/lzma/index_hash.h
536     src/liblzma/api/lzma/lzma12.h
537     src/liblzma/api/lzma/stream_flags.h
538     src/liblzma/api/lzma/version.h
539     src/liblzma/api/lzma/vli.h
542 add_library(liblzma
543     src/common/mythread.h
544     src/common/sysdefs.h
545     src/common/tuklib_common.h
546     src/common/tuklib_config.h
547     src/common/tuklib_integer.h
548     src/common/tuklib_physmem.c
549     src/common/tuklib_physmem.h
550     ${LIBLZMA_API_HEADERS}
551     src/liblzma/check/check.c
552     src/liblzma/check/check.h
553     src/liblzma/check/crc_common.h
554     src/liblzma/check/crc_x86_clmul.h
555     src/liblzma/check/crc32_arm64.h
556     src/liblzma/check/crc32_loongarch.h
557     src/liblzma/common/block_util.c
558     src/liblzma/common/common.c
559     src/liblzma/common/common.h
560     src/liblzma/common/easy_preset.c
561     src/liblzma/common/easy_preset.h
562     src/liblzma/common/filter_common.c
563     src/liblzma/common/filter_common.h
564     src/liblzma/common/hardware_physmem.c
565     src/liblzma/common/index.c
566     src/liblzma/common/index.h
567     src/liblzma/common/memcmplen.h
568     src/liblzma/common/stream_flags_common.c
569     src/liblzma/common/stream_flags_common.h
570     src/liblzma/common/string_conversion.c
571     src/liblzma/common/vli_size.c
574 target_include_directories(liblzma PRIVATE
575     src/liblzma/api
576     src/liblzma/common
577     src/liblzma/check
578     src/liblzma/lz
579     src/liblzma/rangecoder
580     src/liblzma/lzma
581     src/liblzma/delta
582     src/liblzma/simple
583     src/common
587 #############
588 # Threading #
589 #############
591 # Supported threading methods:
592 # yes   - Autodetect the best threading method. The autodetection will
593 #         prefer Windows threading (win95 or vista) over posix if both are
594 #         available. vista threads will be used over win95 unless it is a
595 #         32-bit build. Configuration fails if no threading support is found;
596 #         threading won't be silently disabled.
597 # no    - Disable threading.
598 # posix - Use posix threading (pthreads), or throw an error if not available.
599 # win95 - Use Windows win95 threading, or throw an error if not available.
600 # vista - Use Windows vista threading, or throw an error if not available.
601 set(SUPPORTED_THREADING_METHODS yes no posix win95 vista)
603 set(XZ_THREADS yes CACHE STRING "Threading method: \
604 'yes' to autodetect, 'no' to disable, 'posix' (pthreads), \
605 'win95' (WinXP compatible), 'vista' (needs Windows Vista or later)")
607 # Create dropdown in CMake GUI since only 1 threading method is possible
608 # to select in a build.
609 set_property(CACHE XZ_THREADS
610              PROPERTY STRINGS "${SUPPORTED_THREADING_METHODS}")
612 # This is a flag variable set when win95 threads are used. We must ensure
613 # that the combination of XZ_SMALL and win95 threads is only used with a
614 # compiler that supports the __constructor__ attribute.
615 set(USE_WIN95_THREADS OFF)
617 # This is a flag variable set when posix threading (pthreads) is used.
618 # It's needed when creating liblzma-config.cmake where dependency on
619 # Threads::Threads is only needed with pthreads.
620 set(USE_POSIX_THREADS OFF)
622 if(NOT XZ_THREADS IN_LIST SUPPORTED_THREADING_METHODS)
623     message(FATAL_ERROR "'${XZ_THREADS}' is not a supported threading method")
624 endif()
626 if(XZ_THREADS)
627     # Also set THREADS_PREFER_PTHREAD_FLAG since the flag has no effect
628     # for Windows threading.
629     set(THREADS_PREFER_PTHREAD_FLAG TRUE)
630     find_package(Threads REQUIRED)
632     # If both Windows and posix threading are available, prefer Windows.
633     # Note that on Cygwin, CMAKE_USE_WIN32_THREADS_INIT is false.
634     if(CMAKE_USE_WIN32_THREADS_INIT AND NOT XZ_THREADS STREQUAL "posix")
635         if(XZ_THREADS STREQUAL "win95"
636                 OR (XZ_THREADS STREQUAL "yes" AND CMAKE_SIZEOF_VOID_P EQUAL 4))
637             # Use Windows 95 (and thus XP) compatible threads.
638             # This avoids use of features that were added in
639             # Windows Vista. This is used for 32-bit x86 builds for
640             # compatibility reasons since it makes no measurable difference
641             # in performance compared to Vista threads.
642             set(USE_WIN95_THREADS ON)
643             add_compile_definitions(MYTHREAD_WIN95)
644         else()
645             add_compile_definitions(MYTHREAD_VISTA)
646         endif()
647     elseif(CMAKE_USE_PTHREADS_INIT)
648         if(XZ_THREADS MATCHES "^posix$|^yes$")
649             # The threading library only needs to be explicitly linked
650             # for posix threads, so this is needed for creating
651             # liblzma-config.cmake later.
652             set(USE_POSIX_THREADS ON)
654             target_link_libraries(liblzma PRIVATE Threads::Threads)
655             add_compile_definitions(MYTHREAD_POSIX)
657             # Make the thread libs available in later checks. In practice
658             # only pthread_condattr_setclock check should need this.
659             list(PREPEND CMAKE_REQUIRED_LIBRARIES "${CMAKE_THREAD_LIBS_INIT}")
661             # Check if pthread_condattr_setclock() exists to
662             # use CLOCK_MONOTONIC.
663             if(HAVE_CLOCK_MONOTONIC)
664                 check_symbol_exists(pthread_condattr_setclock pthread.h
665                                     HAVE_PTHREAD_CONDATTR_SETCLOCK)
666                 tuklib_add_definition_if(ALL HAVE_PTHREAD_CONDATTR_SETCLOCK)
667             endif()
668         else()
669             message(SEND_ERROR
670                     "Windows threading method was requested but a compatible "
671                     "library could not be found")
672         endif()
673     else()
674         message(SEND_ERROR "No supported threading library found")
675     endif()
677     target_sources(liblzma PRIVATE
678         src/common/tuklib_cpucores.c
679         src/common/tuklib_cpucores.h
680         src/liblzma/common/hardware_cputhreads.c
681         src/liblzma/common/outqueue.c
682         src/liblzma/common/outqueue.h
683     )
684 endif()
687 ######################
688 # Size optimizations #
689 ######################
691 option(XZ_SMALL "Reduce code size at expense of speed. \
692 This may be useful together with CMAKE_BUILD_TYPE=MinSizeRel.")
694 if(XZ_SMALL)
695     add_compile_definitions(HAVE_SMALL)
696 endif()
699 ##########
700 # Checks #
701 ##########
703 set(SUPPORTED_CHECKS crc32 crc64 sha256)
705 set(XZ_CHECKS "${SUPPORTED_CHECKS}" CACHE STRING
706     "Check types to support (crc32 is always built)")
708 foreach(CHECK IN LISTS XZ_CHECKS)
709     if(NOT CHECK IN_LIST SUPPORTED_CHECKS)
710         message(FATAL_ERROR "'${CHECK}' is not a supported check type")
711     endif()
712 endforeach()
714 if(XZ_SMALL)
715     target_sources(liblzma PRIVATE src/liblzma/check/crc32_small.c)
716 else()
717     target_sources(liblzma PRIVATE
718         src/liblzma/check/crc32_fast.c
719         src/liblzma/check/crc32_table_be.h
720         src/liblzma/check/crc32_table_le.h
721     )
723     if(XZ_ASM_I386)
724         target_sources(liblzma PRIVATE src/liblzma/check/crc32_x86.S)
725         target_compile_definitions(liblzma PRIVATE HAVE_CRC_X86_ASM)
726     endif()
727 endif()
729 if("crc64" IN_LIST XZ_CHECKS)
730     add_compile_definitions("HAVE_CHECK_CRC64")
732     if(XZ_SMALL)
733         target_sources(liblzma PRIVATE src/liblzma/check/crc64_small.c)
734     else()
735         target_sources(liblzma PRIVATE
736             src/liblzma/check/crc64_fast.c
737             src/liblzma/check/crc64_table_be.h
738             src/liblzma/check/crc64_table_le.h
739         )
741         if(XZ_ASM_I386)
742             target_sources(liblzma PRIVATE src/liblzma/check/crc64_x86.S)
743             # Adding #define HAVE_CRC_X86_ASM was already handled in
744             # the CRC32 case a few lines above. CRC32 is always built.
745         endif()
746     endif()
747 endif()
749 # External SHA-256
751 # At least the following implementations are supported:
753 # OS       Headers                     Library  Type           Function
754 # FreeBSD  sys/types.h + sha256.h      libmd    SHA256_CTX     SHA256_Init
755 # NetBSD   sys/types.h + sha2.h                 SHA256_CTX     SHA256_Init
756 # OpenBSD  sys/types.h + sha2.h                 SHA2_CTX       SHA256Init
757 # Solaris  sys/types.h + sha2.h        libmd    SHA256_CTX     SHA256Init
758 # MINIX 3  sys/types.h + sha2.h                 SHA256_CTX     SHA256_Init
759 # Darwin   CommonCrypto/CommonDigest.h          CC_SHA256_CTX  CC_SHA256_Init
761 # Note that Darwin's CC_SHA256_Update takes buffer size as uint32_t instead
762 # of size_t.
764 # This is disabled by default because it used to conflict with OpenSSL
765 # on some platforms and in some cases the builtin code in liblzma was faster.
766 # See INSTALL and the commit message ac398c3bafa6e4c80e20571373a96947db863b3d.
767 option(XZ_EXTERNAL_SHA256 "Use SHA-256 code from the operating system \
768 if possible. See INSTALL for possible subtle problems." OFF)
770 if("sha256" IN_LIST XZ_CHECKS)
771     add_compile_definitions("HAVE_CHECK_SHA256")
773     # Assume that external code won't be used. We need this to know
774     # if the internal sha256.c should be built.
775     set(USE_INTERNAL_SHA256 ON)
777     if(XZ_EXTERNAL_SHA256)
778         # Find the header.
779         set(SHA256_HEADER OFF)
781         foreach(X CommonCrypto/CommonDigest.h sha256.h sha2.h)
782             string(TOUPPER "HAVE_${X}" HAVE_X)
783             string(REGEX REPLACE "[/.]" "_" HAVE_X "${HAVE_X}")
784             check_include_file("${X}" "${HAVE_X}")
785             if(${HAVE_X})
786                 target_compile_definitions(liblzma PRIVATE "${HAVE_X}")
787                 set(SHA256_HEADER "${X}")
788                 break()
789             endif()
790         endforeach()
792         if(SHA256_HEADER)
793             # Find the type to hold the SHA-256 state.
794             set(SHA256_TYPE OFF)
796             foreach(X CC_SHA256_CTX SHA256_CTX SHA2_CTX)
797                 string(TOUPPER "HAVE_${X}" HAVE_X)
799                 # configure.ac uses <sys/types.h> conditionally but it's
800                 # required on all cases except Darwin where it exists too.
801                 # So just use it unconditionally here.
802                 set(SOURCE
803                         "#include <sys/types.h>
804                         #include <${SHA256_HEADER}>
805                         int main(void)
806                         {
807                             ${X} ctx;
808                             return 0;
809                         }")
810                 check_c_source_compiles("${SOURCE}" "${HAVE_X}")
811                 if(${HAVE_X})
812                     target_compile_definitions(liblzma PRIVATE "${HAVE_X}")
813                     set(SHA256_TYPE "${X}")
814                     break()
815                 endif()
816             endforeach()
818             if(SHA256_TYPE)
819                 # Find the initialization function. It might required libmd.
820                 foreach(X CC_SHA256_Init SHA256Init SHA256_Init)
821                     string(TOUPPER "HAVE_${X}" HAVE_X)
823                     # On FreeBSD, <sha256.h> defines the SHA-256 functions as
824                     # macros to rename them for namespace reasons. Avoid
825                     # check_symbol_exists as that would accept macros without
826                     # checking if the program links.
827                     set(SOURCE
828                             "#include <sys/types.h>
829                             #include <${SHA256_HEADER}>
830                             int main(void)
831                             {
832                                 ${SHA256_TYPE} ctx;
833                                 ${X}(&ctx);
834                                 return 0;
835                             }")
837                     check_c_source_compiles("${SOURCE}" "${HAVE_X}")
838                     if(${HAVE_X})
839                         target_compile_definitions(liblzma PRIVATE "${HAVE_X}")
840                         set(USE_INTERNAL_SHA256 OFF)
841                         break()
842                     else()
843                         # Try with libmd. Other checks don't need it so we
844                         # don't need to leave it into CMAKE_REQUIRED_LIBRARIES.
845                         list(PREPEND CMAKE_REQUIRED_LIBRARIES md)
846                         check_c_source_compiles("${SOURCE}" "${HAVE_X}_LIBMD")
847                         list(POP_FRONT CMAKE_REQUIRED_LIBRARIES)
848                         if(${HAVE_X}_LIBMD)
849                             # NOTE: Just "${HAVE_X}", not "${HAVE_X}_LIBMD":
850                             target_compile_definitions(liblzma PRIVATE
851                                                        "${HAVE_X}")
852                             target_link_libraries(liblzma PRIVATE md)
853                             set(LIBS "-lmd ${LIBS}") # For liblzma.pc
854                             set(USE_INTERNAL_SHA256 OFF)
855                             break()
856                         endif()
857                     endif()
858                 endforeach()
859             endif()
860         endif()
861     endif()
863     if(USE_INTERNAL_SHA256)
864         target_sources(liblzma PRIVATE src/liblzma/check/sha256.c)
865     endif()
866 endif()
869 #################
870 # Match finders #
871 #################
873 set(SUPPORTED_MATCH_FINDERS hc3 hc4 bt2 bt3 bt4)
875 set(XZ_MATCH_FINDERS "${SUPPORTED_MATCH_FINDERS}" CACHE STRING
876     "Match finders to support (at least one is required for LZMA1 or LZMA2)")
878 foreach(MF IN LISTS XZ_MATCH_FINDERS)
879     if(MF IN_LIST SUPPORTED_MATCH_FINDERS)
880         string(TOUPPER "${MF}" MF_UPPER)
881         add_compile_definitions("HAVE_MF_${MF_UPPER}")
882     else()
883         message(FATAL_ERROR "'${MF}' is not a supported match finder")
884     endif()
885 endforeach()
888 ############
889 # Encoders #
890 ############
892 set(SIMPLE_FILTERS
893     x86
894     arm
895     armthumb
896     arm64
897     powerpc
898     ia64
899     sparc
900     riscv
903 # The SUPPORTED_FILTERS are shared between Encoders and Decoders
904 # since only lzip does not appear in both lists. lzip is a special
905 # case anyway, so it is handled separately in the Decoders section.
906 set(SUPPORTED_FILTERS
907     lzma1
908     lzma2
909     delta
910     "${SIMPLE_FILTERS}"
913 set(XZ_ENCODERS "${SUPPORTED_FILTERS}" CACHE STRING "Encoders to support")
915 # If LZMA2 is enabled, then LZMA1 must also be enabled.
916 if(NOT "lzma1" IN_LIST XZ_ENCODERS AND "lzma2" IN_LIST XZ_ENCODERS)
917     message(FATAL_ERROR "LZMA2 encoder requires that LZMA1 is also enabled")
918 endif()
920 # If LZMA1 is enabled, then at least one match finder must be enabled.
921 if(XZ_MATCH_FINDERS STREQUAL "" AND "lzma1" IN_LIST XZ_ENCODERS)
922     message(FATAL_ERROR "At least 1 match finder is required for an "
923                         "LZ-based encoder")
924 endif()
926 set(HAVE_DELTA_CODER OFF)
927 set(SIMPLE_ENCODERS OFF)
928 set(HAVE_ENCODERS OFF)
930 foreach(ENCODER IN LISTS XZ_ENCODERS)
931     if(ENCODER IN_LIST SUPPORTED_FILTERS)
932         set(HAVE_ENCODERS ON)
934         if(NOT SIMPLE_ENCODERS AND ENCODER IN_LIST SIMPLE_FILTERS)
935             set(SIMPLE_ENCODERS ON)
936         endif()
938         string(TOUPPER "${ENCODER}" ENCODER_UPPER)
939         add_compile_definitions("HAVE_ENCODER_${ENCODER_UPPER}")
940     else()
941         message(FATAL_ERROR "'${ENCODER}' is not a supported encoder")
942     endif()
943 endforeach()
945 if(HAVE_ENCODERS)
946     add_compile_definitions(HAVE_ENCODERS)
948     target_sources(liblzma PRIVATE
949         src/liblzma/common/alone_encoder.c
950         src/liblzma/common/block_buffer_encoder.c
951         src/liblzma/common/block_buffer_encoder.h
952         src/liblzma/common/block_encoder.c
953         src/liblzma/common/block_encoder.h
954         src/liblzma/common/block_header_encoder.c
955         src/liblzma/common/easy_buffer_encoder.c
956         src/liblzma/common/easy_encoder.c
957         src/liblzma/common/easy_encoder_memusage.c
958         src/liblzma/common/filter_buffer_encoder.c
959         src/liblzma/common/filter_encoder.c
960         src/liblzma/common/filter_encoder.h
961         src/liblzma/common/filter_flags_encoder.c
962         src/liblzma/common/index_encoder.c
963         src/liblzma/common/index_encoder.h
964         src/liblzma/common/stream_buffer_encoder.c
965         src/liblzma/common/stream_encoder.c
966         src/liblzma/common/stream_flags_encoder.c
967         src/liblzma/common/vli_encoder.c
968     )
970     if(XZ_THREADS)
971         target_sources(liblzma PRIVATE
972             src/liblzma/common/stream_encoder_mt.c
973         )
974     endif()
976     if(SIMPLE_ENCODERS)
977         target_sources(liblzma PRIVATE
978             src/liblzma/simple/simple_encoder.c
979             src/liblzma/simple/simple_encoder.h
980         )
981     endif()
983     if("lzma1" IN_LIST XZ_ENCODERS)
984         target_sources(liblzma PRIVATE
985             src/liblzma/lzma/lzma_encoder.c
986             src/liblzma/lzma/lzma_encoder.h
987             src/liblzma/lzma/lzma_encoder_optimum_fast.c
988             src/liblzma/lzma/lzma_encoder_optimum_normal.c
989             src/liblzma/lzma/lzma_encoder_private.h
990             src/liblzma/lzma/fastpos.h
991             src/liblzma/lz/lz_encoder.c
992             src/liblzma/lz/lz_encoder.h
993             src/liblzma/lz/lz_encoder_hash.h
994             src/liblzma/lz/lz_encoder_hash_table.h
995             src/liblzma/lz/lz_encoder_mf.c
996             src/liblzma/rangecoder/price.h
997             src/liblzma/rangecoder/price_table.c
998             src/liblzma/rangecoder/range_encoder.h
999         )
1001         if(NOT XZ_SMALL)
1002             target_sources(liblzma PRIVATE src/liblzma/lzma/fastpos_table.c)
1003         endif()
1004     endif()
1006     if("lzma2" IN_LIST XZ_ENCODERS)
1007         target_sources(liblzma PRIVATE
1008             src/liblzma/lzma/lzma2_encoder.c
1009             src/liblzma/lzma/lzma2_encoder.h
1010         )
1011     endif()
1013     if("delta" IN_LIST XZ_ENCODERS)
1014         set(HAVE_DELTA_CODER ON)
1015         target_sources(liblzma PRIVATE
1016             src/liblzma/delta/delta_encoder.c
1017             src/liblzma/delta/delta_encoder.h
1018         )
1019     endif()
1020 endif()
1023 ############
1024 # Decoders #
1025 ############
1027 set(XZ_DECODERS "${SUPPORTED_FILTERS}" CACHE STRING "Decoders to support")
1029 set(SIMPLE_DECODERS OFF)
1030 set(HAVE_DECODERS OFF)
1032 foreach(DECODER IN LISTS XZ_DECODERS)
1033     if(DECODER IN_LIST SUPPORTED_FILTERS)
1034         set(HAVE_DECODERS ON)
1036         if(NOT SIMPLE_DECODERS AND DECODER IN_LIST SIMPLE_FILTERS)
1037             set(SIMPLE_DECODERS ON)
1038         endif()
1040         string(TOUPPER "${DECODER}" DECODER_UPPER)
1041         add_compile_definitions("HAVE_DECODER_${DECODER_UPPER}")
1042     else()
1043         message(FATAL_ERROR "'${DECODER}' is not a supported decoder")
1044     endif()
1045 endforeach()
1047 if(HAVE_DECODERS)
1048     add_compile_definitions(HAVE_DECODERS)
1050     target_sources(liblzma PRIVATE
1051         src/liblzma/common/alone_decoder.c
1052         src/liblzma/common/alone_decoder.h
1053         src/liblzma/common/auto_decoder.c
1054         src/liblzma/common/block_buffer_decoder.c
1055         src/liblzma/common/block_decoder.c
1056         src/liblzma/common/block_decoder.h
1057         src/liblzma/common/block_header_decoder.c
1058         src/liblzma/common/easy_decoder_memusage.c
1059         src/liblzma/common/file_info.c
1060         src/liblzma/common/filter_buffer_decoder.c
1061         src/liblzma/common/filter_decoder.c
1062         src/liblzma/common/filter_decoder.h
1063         src/liblzma/common/filter_flags_decoder.c
1064         src/liblzma/common/index_decoder.c
1065         src/liblzma/common/index_decoder.h
1066         src/liblzma/common/index_hash.c
1067         src/liblzma/common/stream_buffer_decoder.c
1068         src/liblzma/common/stream_decoder.c
1069         src/liblzma/common/stream_flags_decoder.c
1070         src/liblzma/common/stream_decoder.h
1071         src/liblzma/common/vli_decoder.c
1072     )
1074     if(XZ_THREADS)
1075         target_sources(liblzma PRIVATE
1076             src/liblzma/common/stream_decoder_mt.c
1077         )
1078     endif()
1080     if(SIMPLE_DECODERS)
1081         target_sources(liblzma PRIVATE
1082             src/liblzma/simple/simple_decoder.c
1083             src/liblzma/simple/simple_decoder.h
1084         )
1085     endif()
1087     if("lzma1" IN_LIST XZ_DECODERS)
1088         target_sources(liblzma PRIVATE
1089             src/liblzma/lzma/lzma_decoder.c
1090             src/liblzma/lzma/lzma_decoder.h
1091             src/liblzma/rangecoder/range_decoder.h
1092             src/liblzma/lz/lz_decoder.c
1093             src/liblzma/lz/lz_decoder.h
1094         )
1095     endif()
1097     if("lzma2" IN_LIST XZ_DECODERS)
1098         target_sources(liblzma PRIVATE
1099             src/liblzma/lzma/lzma2_decoder.c
1100             src/liblzma/lzma/lzma2_decoder.h
1101         )
1102     endif()
1104     if("delta" IN_LIST XZ_DECODERS)
1105         set(HAVE_DELTA_CODER ON)
1106         target_sources(liblzma PRIVATE
1107             src/liblzma/delta/delta_decoder.c
1108             src/liblzma/delta/delta_decoder.h
1109         )
1110     endif()
1111 endif()
1113 # Some sources must appear if the filter is configured as either
1114 # an encoder or decoder.
1115 if("lzma1" IN_LIST XZ_ENCODERS OR "lzma1" IN_LIST XZ_DECODERS)
1116     target_sources(liblzma PRIVATE
1117         src/liblzma/rangecoder/range_common.h
1118         src/liblzma/lzma/lzma_encoder_presets.c
1119         src/liblzma/lzma/lzma_common.h
1120     )
1121 endif()
1123 if(HAVE_DELTA_CODER)
1124     target_sources(liblzma PRIVATE
1125         src/liblzma/delta/delta_common.c
1126         src/liblzma/delta/delta_common.h
1127         src/liblzma/delta/delta_private.h
1128     )
1129 endif()
1131 if(SIMPLE_ENCODERS OR SIMPLE_DECODERS)
1132     target_sources(liblzma PRIVATE
1133         src/liblzma/simple/simple_coder.c
1134         src/liblzma/simple/simple_coder.h
1135         src/liblzma/simple/simple_private.h
1136     )
1137 endif()
1139 foreach(SIMPLE_CODER IN LISTS SIMPLE_FILTERS)
1140     if(SIMPLE_CODER IN_LIST XZ_ENCODERS OR SIMPLE_CODER IN_LIST XZ_DECODERS)
1141         target_sources(liblzma PRIVATE "src/liblzma/simple/${SIMPLE_CODER}.c")
1142     endif()
1143 endforeach()
1146 #############
1147 # MicroLZMA #
1148 #############
1150 option(XZ_MICROLZMA_ENCODER
1151        "MicroLZMA encoder (needed by specific applications only)" ON)
1153 option(XZ_MICROLZMA_DECODER
1154        "MicroLZMA decoder (needed by specific applications only)" ON)
1156 if(XZ_MICROLZMA_ENCODER)
1157     if(NOT "lzma1" IN_LIST XZ_ENCODERS)
1158         message(FATAL_ERROR "The LZMA1 encoder is required to support the "
1159                             "MicroLZMA encoder")
1160     endif()
1162     target_sources(liblzma PRIVATE src/liblzma/common/microlzma_encoder.c)
1163 endif()
1165 if(XZ_MICROLZMA_DECODER)
1166     if(NOT "lzma1" IN_LIST XZ_DECODERS)
1167         message(FATAL_ERROR "The LZMA1 decoder is required to support the "
1168                             "MicroLZMA decoder")
1169     endif()
1171     target_sources(liblzma PRIVATE src/liblzma/common/microlzma_decoder.c)
1172 endif()
1175 #############################
1176 # lzip (.lz) format support #
1177 #############################
1179 option(XZ_LZIP_DECODER "Support lzip decoder" ON)
1181 if(XZ_LZIP_DECODER)
1182     # If lzip decoder support is requested, make sure LZMA1 decoder is enabled.
1183     if(NOT "lzma1" IN_LIST XZ_DECODERS)
1184         message(FATAL_ERROR "The LZMA1 decoder is required to support the "
1185                             "lzip decoder")
1186     endif()
1188     add_compile_definitions(HAVE_LZIP_DECODER)
1190     target_sources(liblzma PRIVATE
1191         src/liblzma/common/lzip_decoder.c
1192         src/liblzma/common/lzip_decoder.h
1193     )
1194 endif()
1198 # Put the tuklib functions under the lzma_ namespace.
1199 target_compile_definitions(liblzma PRIVATE TUKLIB_SYMBOL_PREFIX=lzma_)
1200 tuklib_cpucores(liblzma)
1201 tuklib_physmem(liblzma)
1203 # While liblzma can be built without tuklib_cpucores or tuklib_physmem
1204 # modules, the liblzma API functions lzma_cputhreads() and lzma_physmem()
1205 # will then be useless (which isn't too bad but still unfortunate). Since
1206 # I expect the CMake-based builds to be only used on systems that are
1207 # supported by these tuklib modules, problems with these tuklib modules
1208 # are considered a hard error for now. This hopefully helps to catch bugs
1209 # in the CMake versions of the tuklib checks.
1210 if(NOT TUKLIB_CPUCORES_FOUND OR NOT TUKLIB_PHYSMEM_FOUND)
1211     # Use SEND_ERROR instead of FATAL_ERROR. If someone reports a bug,
1212     # seeing the results of the remaining checks can be useful too.
1213     message(SEND_ERROR
1214             "tuklib_cpucores() or tuklib_physmem() failed. "
1215             "Unless you really are building for a system where these "
1216             "modules are not supported (unlikely), this is a bug in the "
1217             "included cmake/tuklib_*.cmake files that should be fixed. "
1218             "To build anyway, edit this CMakeLists.txt to ignore this error.")
1219 endif()
1221 # Check for __attribute__((__constructor__)) support.
1222 # This needs -Werror because some compilers just warn
1223 # about this being unsupported.
1224 cmake_push_check_state()
1225 set(CMAKE_REQUIRED_FLAGS "-Werror")
1226 check_c_source_compiles("
1227         __attribute__((__constructor__))
1228         static void my_constructor_func(void) { return; }
1229         int main(void) { return 0; }
1230     "
1231     HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
1232 cmake_pop_check_state()
1233 tuklib_add_definition_if(liblzma HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
1235 # The Win95 threading lacks a thread-safe one-time initialization function.
1236 # The one-time initialization is needed for crc32_small.c and crc64_small.c
1237 # create the CRC tables. So if small mode is enabled, the threading mode is
1238 # win95, and the compiler does not support attribute constructor, then we
1239 # would end up with a multithreaded build that is thread-unsafe. As a
1240 # result this configuration is not allowed.
1241 if(USE_WIN95_THREADS AND XZ_SMALL AND NOT HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
1242     message(SEND_ERROR "Threading method win95 and XZ_SMALL "
1243                        "cannot be used at the same time because the compiler "
1244                        "doesn't support __attribute__((__constructor__))")
1245 endif()
1248 # cpuid.h
1249 check_include_file(cpuid.h HAVE_CPUID_H)
1250 tuklib_add_definition_if(liblzma HAVE_CPUID_H)
1252 # immintrin.h:
1253 check_include_file(immintrin.h HAVE_IMMINTRIN_H)
1254 if(HAVE_IMMINTRIN_H)
1255     target_compile_definitions(liblzma PRIVATE HAVE_IMMINTRIN_H)
1257     # SSE2 intrinsics:
1258     check_c_source_compiles("
1259             #include <immintrin.h>
1260             int main(void)
1261             {
1262                 __m128i x = { 0 };
1263                 _mm_movemask_epi8(x);
1264                 return 0;
1265             }
1266         "
1267         HAVE__MM_MOVEMASK_EPI8)
1268     tuklib_add_definition_if(liblzma HAVE__MM_MOVEMASK_EPI8)
1270     # CLMUL intrinsic:
1271     option(XZ_CLMUL_CRC "Use carryless multiplication for CRC \
1272 calculation (with runtime detection) if supported by the compiler" ON)
1274     if(XZ_CLMUL_CRC)
1275         check_c_source_compiles("
1276                 #include <immintrin.h>
1277                 #if defined(__e2k__) && __iset__ < 6
1278                 #   error
1279                 #endif
1280                 #if (defined(__GNUC__) || defined(__clang__)) \
1281                         && !defined(__EDG__)
1282                 __attribute__((__target__(\"ssse3,sse4.1,pclmul\")))
1283                 #endif
1284                 int main(void)
1285                 {
1286                     __m128i a = _mm_set_epi64x(1, 2);
1287                     a = _mm_clmulepi64_si128(a, a, 0);
1288                     return 0;
1289                 }
1290             "
1291             HAVE_USABLE_CLMUL)
1292         tuklib_add_definition_if(liblzma HAVE_USABLE_CLMUL)
1293     endif()
1294 endif()
1296 # ARM64 C Language Extensions define CRC32 functions in arm_acle.h.
1297 # These are supported by at least GCC and Clang which both need
1298 # __attribute__((__target__("+crc"))), unless the needed compiler flags
1299 # are used to support the CRC instruction.
1300 option(XZ_ARM64_CRC32 "Use ARM64 CRC32 instructions (with runtime detection) \
1301 if supported by the compiler" ON)
1303 if(XZ_ARM64_CRC32)
1304     check_c_source_compiles("
1305             #include <stdint.h>
1307             #ifndef _MSC_VER
1308             #include <arm_acle.h>
1309             #endif
1311             #if (defined(__GNUC__) || defined(__clang__)) && !defined(__EDG__)
1312             __attribute__((__target__(\"+crc\")))
1313             #endif
1314             int main(void)
1315             {
1316                 return __crc32d(1, 2) != 0;
1317             }
1318         "
1319         HAVE_ARM64_CRC32)
1321     if(HAVE_ARM64_CRC32)
1322         target_compile_definitions(liblzma PRIVATE HAVE_ARM64_CRC32)
1324         # Check for ARM64 CRC32 instruction runtime detection.
1325         # getauxval() is supported on Linux.
1326         check_symbol_exists(getauxval sys/auxv.h HAVE_GETAUXVAL)
1327         tuklib_add_definition_if(liblzma HAVE_GETAUXVAL)
1329         # elf_aux_info() is supported on FreeBSD and OpenBSD >= 7.6.
1330         check_symbol_exists(elf_aux_info sys/auxv.h HAVE_ELF_AUX_INFO)
1331         tuklib_add_definition_if(liblzma HAVE_ELF_AUX_INFO)
1333         # sysctlbyname("hw.optional.armv8_crc32", ...) is supported on Darwin
1334         # (macOS, iOS, etc.). Note that sysctlbyname() is supported on FreeBSD,
1335         # NetBSD, and possibly others too but the string is specific to
1336         # Apple OSes. The C code is responsible for checking
1337         # defined(__APPLE__) before using
1338         # sysctlbyname("hw.optional.armv8_crc32", ...).
1339         check_symbol_exists(sysctlbyname sys/sysctl.h HAVE_SYSCTLBYNAME)
1340         tuklib_add_definition_if(liblzma HAVE_SYSCTLBYNAME)
1341     endif()
1342 endif()
1344 option(XZ_LOONGARCH_CRC32
1345        "Use LoongArch CRC32 instructions if supported by the compiler" ON)
1347 if(XZ_LOONGARCH_CRC32)
1348     # LoongArch CRC32 intrinsics are in larchintrin.h.
1349     # These are supported by at least GCC and Clang.
1350     #
1351     # Only 64-bit LoongArch is currently supported.
1352     # It doesn't need runtime detection.
1353     check_c_source_compiles("
1354             #if !(defined(__loongarch__) && __loongarch_grlen >= 64)
1355             #   error
1356             #endif
1358             #include <larchintrin.h>
1359             int main(void)
1360             {
1361                 return __crc_w_w_w(1, 2);
1362             }
1363         "
1364         HAVE_LOONGARCH_CRC32)
1365     tuklib_add_definition_if(liblzma HAVE_LOONGARCH_CRC32)
1366 endif()
1369 # Symbol visibility support:
1371 # The C_VISIBILITY_PRESET property takes care of adding the compiler
1372 # option -fvisibility=hidden (or equivalent) if and only if it is supported.
1374 # HAVE_VISIBILITY should always be defined to 0 or 1. It tells liblzma
1375 # if __attribute__((__visibility__("default")))
1376 # and __attribute__((__visibility__("hidden"))) are supported.
1377 # Those are useful only when the compiler supports -fvisibility=hidden
1378 # or such option so HAVE_VISIBILITY should be 1 only when both option and
1379 # the attribute support are present. HAVE_VISIBILITY is ignored on Windows
1380 # and Cygwin by the liblzma C code; __declspec(dllexport) is used instead.
1382 # CMake's GenerateExportHeader module is too fancy since liblzma already
1383 # has the necessary macros. Instead, check CMake's internal variable
1384 # CMAKE_C_COMPILE_OPTIONS_VISIBILITY (it's the C-specific variant of
1385 # CMAKE_<LANG>_COMPILE_OPTIONS_VISIBILITY) which contains the compiler
1386 # command line option for visibility support. It's empty or unset when
1387 # visibility isn't supported. (It was added to CMake 2.8.12 in the commit
1388 # 0e9f4bc00c6b26f254e74063e4026ac33b786513 in 2013.) This way we don't
1389 # set HAVE_VISIBILITY to 1 when visibility isn't actually supported.
1390 if(BUILD_SHARED_LIBS AND CMAKE_C_COMPILE_OPTIONS_VISIBILITY)
1391     set_target_properties(liblzma PROPERTIES C_VISIBILITY_PRESET hidden)
1392     target_compile_definitions(liblzma PRIVATE HAVE_VISIBILITY=1)
1393 else()
1394     target_compile_definitions(liblzma PRIVATE HAVE_VISIBILITY=0)
1395 endif()
1397 if(WIN32 OR CYGWIN)
1398     if(BUILD_SHARED_LIBS)
1399         # Add the Windows resource file for liblzma.dll.
1400         target_sources(liblzma PRIVATE src/liblzma/liblzma_w32res.rc)
1402         set_source_files_properties(src/liblzma/liblzma_w32res.rc PROPERTIES
1403             OBJECT_DEPENDS "${W32RES_DEPENDENCIES}"
1404         )
1406         # Export the public API symbols with __declspec(dllexport).
1407         target_compile_definitions(liblzma PRIVATE DLL_EXPORT)
1409         if(NOT MSVC AND NOT CYGWIN)
1410             # Create a DEF file. The Autotools-based build creates a DEF file
1411             # under Cygwin & MSYS2 too but it almost certainly is a useless
1412             # file in that context, so the CMake build omits it.
1413             #
1414             # The linker puts the ordinal numbers in the DEF file
1415             # too so the output from the linker isn't our final file.
1416             target_link_options(liblzma PRIVATE
1417                                 "-Wl,--output-def,liblzma.def.in")
1419             # Remove the ordinal numbers from the DEF file so that
1420             # no one will create an import library that links by ordinal
1421             # instead of by name. We don't maintain a DEF file so the
1422             # ordinal numbers aren't stable.
1423             add_custom_command(TARGET liblzma POST_BUILD
1424                 COMMAND "${CMAKE_COMMAND}"
1425                     -DINPUT_FILE=liblzma.def.in
1426                     -DOUTPUT_FILE=liblzma.def
1427                     -P
1428                     "${CMAKE_CURRENT_SOURCE_DIR}/cmake/remove-ordinals.cmake"
1429                 BYPRODUCTS "liblzma.def"
1430                 VERBATIM)
1431         endif()
1432     else()
1433         # Disable __declspec(dllimport) when linking against static liblzma.
1434         target_compile_definitions(liblzma INTERFACE LZMA_API_STATIC)
1435     endif()
1436 elseif(BUILD_SHARED_LIBS AND SYMBOL_VERSIONING STREQUAL "linux")
1437     # Note that adding link options doesn't affect static builds
1438     # but HAVE_SYMBOL_VERSIONS_LINUX must not be used with static builds
1439     # because it would put symbol versions into the static library which
1440     # can cause problems. It's clearer if all symver related things are
1441     # omitted when not building a shared library.
1442     #
1443     # NOTE: Set it explicitly to 1 to make it clear that versioning is
1444     # done unconditionally in the C files.
1445     target_compile_definitions(liblzma PRIVATE HAVE_SYMBOL_VERSIONS_LINUX=1)
1446     target_link_options(liblzma PRIVATE
1447         "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_linux.map"
1448     )
1449     set_target_properties(liblzma PROPERTIES
1450         LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_linux.map"
1451     )
1452 elseif(BUILD_SHARED_LIBS AND SYMBOL_VERSIONING STREQUAL "generic")
1453     target_link_options(liblzma PRIVATE
1454         "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_generic.map"
1455     )
1456     set_target_properties(liblzma PROPERTIES
1457         LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_generic.map"
1458     )
1459 endif()
1461 set_target_properties(liblzma PROPERTIES
1462     # At least for now the package versioning matches the rules used for
1463     # shared library versioning (excluding development releases) so it is
1464     # fine to use the package version here.
1465     SOVERSION "${xz_VERSION_MAJOR}"
1466     VERSION "${xz_VERSION}"
1468     # The name liblzma a mess because in many places "lib" is just a prefix
1469     # and not part of the actual name. (Don't name a new library this way!)
1470     # Cygwin uses "cyg", MSYS2 uses "msys-", and some platforms use no prefix.
1471     # However, we want to avoid lzma.dll on Windows as that would conflict
1472     # with LZMA SDK. liblzma has been liblzma.dll on Windows since the
1473     # beginning so try to stick with it.
1474     #
1475     # Up to XZ Utils 5.6.2 we set PREFIX and IMPORT_PREFIX properties to ""
1476     # while keeping the default "liblzma" OUTPUT_NAME that was derived from
1477     # the target name. But this broke naming on Cygwin and MSYS2.
1478     #
1479     # Setting OUTPUT_NAME without the "lib" prefix means that CMake will add
1480     # the platform-specific prefix as needed. So on most systems CMake will
1481     # add "lib" but on Cygwin and MSYS2 the naming will be correct too.
1482     #
1483     # On Windows, CMake uses the "lib" prefix with MinGW-w64 but not with
1484     # other toolchains. Those those need to be handled specially to get
1485     # the DLL file named liblzma.dll instead of lzma.dll.
1486     OUTPUT_NAME "lzma"
1489 if(WIN32 AND NOT MINGW)
1490     # Up to XZ Utils 5.6.2 and building with MSVC, we produced liblzma.dll
1491     # and liblzma.lib. The downside of liblzma.lib is that it's not
1492     # compatible with pkgconf usage. liblzma.pc contains "-llzma" which
1493     # "pkgconf --msvc-syntax --libs liblzma" converts to "lzma.lib".
1494     # So as a compromise, we can keep the liblzma.dll name but the import
1495     # library and static liblzma need to be named lzma.lib so that pkgconf
1496     # can be used with MSVC. (MinGW-w64 finds both names with "-llzma".)
1497     set_target_properties(liblzma PROPERTIES RUNTIME_OUTPUT_NAME "liblzma")
1498 endif()
1500 # Create liblzma-config-version.cmake.
1502 # FIXME: SameMajorVersion is correct for stable releases but it is wrong
1503 # for development releases where each release may have incompatible changes.
1504 include(CMakePackageConfigHelpers)
1505 write_basic_package_version_file(
1506     "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config-version.cmake"
1507     VERSION "${xz_VERSION}"
1508     COMPATIBILITY SameMajorVersion)
1510 # Create liblzma-config.cmake. We use this spelling instead of
1511 # liblzmaConfig.cmake to make find_package work in case insensitive
1512 # manner even with case sensitive file systems. This gives more consistent
1513 # behavior between operating systems. This optionally includes a dependency
1514 # on a threading library, so the contents are created in two separate parts.
1515 # The "second half" is always needed, so create it first.
1516 set(LZMA_CONFIG_CONTENTS
1517 "include(\"\${CMAKE_CURRENT_LIST_DIR}/liblzma-targets.cmake\")
1519 if(NOT TARGET LibLZMA::LibLZMA)
1520     # Be compatible with the spelling used by the FindLibLZMA module. This
1521     # doesn't use ALIAS because it would make CMake resolve LibLZMA::LibLZMA
1522     # to liblzma::liblzma instead of keeping the original spelling. Keeping
1523     # the original spelling is important for good FindLibLZMA compatibility.
1524     add_library(LibLZMA::LibLZMA INTERFACE IMPORTED)
1525     set_target_properties(LibLZMA::LibLZMA PROPERTIES
1526                           INTERFACE_LINK_LIBRARIES liblzma::liblzma)
1527 endif()
1530 if(USE_POSIX_THREADS)
1531     set(LZMA_CONFIG_CONTENTS
1532 "include(CMakeFindDependencyMacro)
1533 set(THREADS_PREFER_PTHREAD_FLAG TRUE)
1534 find_dependency(Threads)
1536 ${LZMA_CONFIG_CONTENTS}
1538 endif()
1540 file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config.cmake"
1541         "${LZMA_CONFIG_CONTENTS}")
1544 # Create liblzma.pc. If CMAKE_INSTALL_<dir> paths are relative to
1545 # CMAKE_INSTALL_PREFIX, the .pc file will be relocatable (that is,
1546 # all paths will be relative to ${prefix}). Otherwise absolute
1547 # paths will be used.
1548 set(prefix "${CMAKE_INSTALL_PREFIX}")
1549 set(exec_prefix "\${prefix}")
1550 cmake_path(APPEND libdir "\${exec_prefix}" "${CMAKE_INSTALL_LIBDIR}")
1551 cmake_path(APPEND includedir "\${prefix}" "${CMAKE_INSTALL_INCLUDEDIR}")
1553 # Threads::Threads is linked in only when using POSIX threads.
1554 # Use an empty value if using Windows threads or if threading is disabled.
1555 set(PTHREAD_CFLAGS)
1556 if(USE_POSIX_THREADS)
1557     set(PTHREAD_CFLAGS "${CMAKE_THREAD_LIBS_INIT}")
1558 endif()
1560 configure_file(src/liblzma/liblzma.pc.in liblzma.pc @ONLY)
1563 # Install the library binary. The INCLUDES specifies the include path that
1564 # is exported for other projects to use but it doesn't install any files.
1565 install(TARGETS liblzma EXPORT liblzmaTargets
1566         RUNTIME  DESTINATION "${CMAKE_INSTALL_BINDIR}"
1567                  COMPONENT liblzma_Runtime
1568         LIBRARY  DESTINATION "${CMAKE_INSTALL_LIBDIR}"
1569                  COMPONENT liblzma_Runtime
1570                  NAMELINK_COMPONENT liblzma_Development
1571         ARCHIVE  DESTINATION "${CMAKE_INSTALL_LIBDIR}"
1572                  COMPONENT liblzma_Development
1573         INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
1575 # Install the liblzma API headers. These use a subdirectory so
1576 # this has to be done as a separate step.
1577 install(DIRECTORY src/liblzma/api/
1578         COMPONENT liblzma_Development
1579         DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
1580         FILES_MATCHING PATTERN "*.h")
1582 # Install the CMake files that other packages can use to find liblzma.
1583 set(XZ_INSTALL_CMAKEDIR
1584     "${CMAKE_INSTALL_LIBDIR}/cmake/liblzma"
1585     CACHE STRING "Path to liblzma's .cmake files")
1587 install(EXPORT liblzmaTargets
1588         NAMESPACE liblzma::
1589         FILE liblzma-targets.cmake
1590         DESTINATION "${XZ_INSTALL_CMAKEDIR}"
1591         COMPONENT liblzma_Development)
1593 install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config.cmake"
1594               "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config-version.cmake"
1595         DESTINATION "${XZ_INSTALL_CMAKEDIR}"
1596         COMPONENT liblzma_Development)
1598 install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblzma.pc"
1599         DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig"
1600         COMPONENT liblzma_Development)
1603 #############################################################################
1604 # Helper functions for installing files
1605 #############################################################################
1607 # For each non-empty element in the list LINK_NAMES, creates symbolic links
1608 # ${LINK_NAME}${LINK_SUFFIX} -> ${TARGET_NAME} in the directory ${DIR}.
1609 # The target file should exist because on Cygwin and MSYS2 symlink creation
1610 # can fail under certain conditions if the target doesn't exist.
1611 function(my_install_symlinks COMPONENT DIR TARGET_NAME LINK_SUFFIX LINK_NAMES)
1612     install(CODE "set(D \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/${DIR}\")
1613                  foreach(L ${LINK_NAMES})
1614                      file(CREATE_LINK \"${TARGET_NAME}\"
1615                                       \"\${D}/\${L}${LINK_SUFFIX}\"
1616                                       SYMBOLIC)
1617                  endforeach()"
1618             COMPONENT "${COMPONENT}")
1619 endfunction()
1621 # Installs a man page file of a given language ("" for the untranslated file)
1622 # and optionally its alternative names as symlinks. This is a helper function
1623 # for my_install_man() below.
1624 function(my_install_man_lang COMPONENT SRC_FILE MAN_LANG LINK_NAMES)
1625     # Get the man page section from the filename suffix.
1626     string(REGEX REPLACE "^.*\.([^/.]+)$" "\\1" MAN_SECTION "${SRC_FILE}")
1628     # A few man pages might be missing from translations.
1629     # Don't attempt to install them or create the related symlinks.
1630     if(NOT MAN_LANG STREQUAL "" AND NOT EXISTS "${SRC_FILE}")
1631         return()
1632     endif()
1634     # Installing the file must be done before creating the symlinks
1635     # due to Cygwin and MSYS2.
1636     install(FILES "${SRC_FILE}"
1637             DESTINATION "${CMAKE_INSTALL_MANDIR}/${MAN_LANG}/man${MAN_SECTION}"
1638             COMPONENT "${COMPONENT}")
1640     # Get the basename of the file to be used as the symlink target.
1641     get_filename_component(BASENAME "${SRC_FILE}" NAME)
1643     # LINK_NAMES don't contain the man page filename suffix (like ".1")
1644     # so it needs to be told to my_install_symlinks.
1645     my_install_symlinks("${COMPONENT}"
1646                         "${CMAKE_INSTALL_MANDIR}/${MAN_LANG}/man${MAN_SECTION}"
1647                         "${BASENAME}" ".${MAN_SECTION}" "${LINK_NAMES}")
1648 endfunction()
1650 # Installs a man page file and optionally its alternative names as symlinks.
1651 # Does the same for translations if XZ_NLS.
1652 function(my_install_man COMPONENT SRC_FILE LINK_NAMES)
1653     my_install_man_lang("${COMPONENT}" "${SRC_FILE}" "" "${LINK_NAMES}")
1655     if(XZ_NLS)
1656         # Find the translated versions of this man page.
1657         get_filename_component(BASENAME "${SRC_FILE}" NAME)
1658         file(GLOB MAN_FILES "po4a/man/*/${BASENAME}")
1660         foreach(F ${MAN_FILES})
1661             get_filename_component(MAN_LANG "${F}" DIRECTORY)
1662             get_filename_component(MAN_LANG "${MAN_LANG}" NAME)
1663             my_install_man_lang("${COMPONENT}" "${F}" "${MAN_LANG}"
1664                                 "${LINK_NAMES}")
1665         endforeach()
1666     endif()
1667 endfunction()
1670 #############################################################################
1671 # libgnu (getopt_long)
1672 #############################################################################
1674 # This mirrors how the Autotools build system handles the getopt_long
1675 # replacement, calling the object library libgnu since the replacement
1676 # version comes from Gnulib.
1677 add_library(libgnu OBJECT)
1679 # CMake requires that even an object library must have at least once source
1680 # file. So we give it a header file that results in no output files.
1682 # NOTE: Using a file outside the lib directory makes it possible to
1683 # delete lib/*.h and lib/*.c and still keep the build working if
1684 # getopt_long replacement isn't needed. It's convenient if one wishes
1685 # to be certain that no GNU LGPL code gets included in the binaries.
1686 target_sources(libgnu PRIVATE src/common/sysdefs.h)
1688 # The Ninja Generator requires setting the linker language since it cannot
1689 # guess the programming language of just a header file. Setting this
1690 # property avoids needing an empty .c file or an non-empty unnecessary .c
1691 # file.
1692 set_target_properties(libgnu PROPERTIES LINKER_LANGUAGE C)
1694 # Create /lib directory in the build directory and add it to the include path.
1695 file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/lib")
1696 target_include_directories(libgnu PUBLIC "${CMAKE_CURRENT_BINARY_DIR}/lib")
1698 # Include /lib from the source directory. It does no harm even if none of
1699 # the Gnulib replacements are used.
1700 target_include_directories(libgnu PUBLIC lib)
1702 # The command line tools need getopt_long in order to parse arguments. If
1703 # the system does not have a getopt_long implementation we can use the one
1704 # from Gnulib instead.
1705 check_symbol_exists(getopt_long getopt.h HAVE_GETOPT_LONG)
1707 if(NOT HAVE_GETOPT_LONG)
1708     # Set the __GETOPT_PREFIX definition to "rpl_" (replacement) to avoid
1709     # name conflicts with libc symbols. The same prefix is set if using
1710     # the Autotools build (m4/getopt.m4).
1711     target_compile_definitions(libgnu PUBLIC "__GETOPT_PREFIX=rpl_")
1713     # Copy the getopt header to the build directory and re-copy it
1714     # if it is updated. (Gnulib does it this way because it allows
1715     # choosing which .in.h files to actually use in the build. We
1716     # need just getopt.h so this is a bit overcomplicated for
1717     # a single header file only.)
1718     configure_file("${CMAKE_CURRENT_SOURCE_DIR}/lib/getopt.in.h"
1719                    "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1720                    COPYONLY)
1722     target_sources(libgnu PRIVATE
1723         lib/getopt1.c
1724         lib/getopt.c
1725         lib/getopt_int.h
1726         lib/getopt-cdefs.h
1727         lib/getopt-core.h
1728         lib/getopt-ext.h
1729         lib/getopt-pfx-core.h
1730         lib/getopt-pfx-ext.h
1731         "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1732     )
1733 endif()
1736 #############################################################################
1737 # Sandboxing for the command line tools
1738 #############################################################################
1740 # auto      Use sandboxing if a supported method is available in the OS.
1741 # no        Disable sandboxing.
1742 # capsicum  Require Capsicum (FreeBSD >= 10.2) and fail if not found.
1743 # pledge    Require pledge(2) (OpenBSD >= 5.9) and fail if not found.
1744 # landlock  Require Landlock (Linux >= 5.13) and fail if not found.
1745 set(SUPPORTED_SANDBOX_METHODS auto no capsicum pledge landlock)
1747 set(XZ_SANDBOX auto CACHE STRING
1748     "Sandboxing method to use in 'xz', 'xzdec', and 'lzmadec'")
1750 set_property(CACHE XZ_SANDBOX PROPERTY STRINGS "${SUPPORTED_SANDBOX_METHODS}")
1752 if(NOT XZ_SANDBOX IN_LIST SUPPORTED_SANDBOX_METHODS)
1753     message(FATAL_ERROR "'${XZ_SANDBOX}' is not a supported "
1754                         "sandboxing method")
1755 endif()
1757 # When autodetecting, the search order is fixed and we must not find
1758 # more than one method.
1759 if(XZ_SANDBOX STREQUAL "no")
1760     set(SANDBOX_FOUND ON)
1761 else()
1762     set(SANDBOX_FOUND OFF)
1763 endif()
1765 # Since xz and xzdec can both use sandboxing, the compile definition needed
1766 # to use the sandbox must be added to both targets.
1767 set(SANDBOX_COMPILE_DEFINITION OFF)
1769 # Sandboxing: Capsicum
1770 if(NOT SANDBOX_FOUND AND XZ_SANDBOX MATCHES "^auto$|^capsicum$")
1771     check_symbol_exists(cap_rights_limit sys/capsicum.h
1772                         HAVE_CAP_RIGHTS_LIMIT)
1773     if(HAVE_CAP_RIGHTS_LIMIT)
1774         set(SANDBOX_COMPILE_DEFINITION "HAVE_CAP_RIGHTS_LIMIT")
1775         set(SANDBOX_FOUND ON)
1776     endif()
1777 endif()
1779 # Sandboxing: pledge(2)
1780 if(NOT SANDBOX_FOUND AND XZ_SANDBOX MATCHES "^auto$|^pledge$")
1781     check_symbol_exists(pledge unistd.h HAVE_PLEDGE)
1782     if(HAVE_PLEDGE)
1783         set(SANDBOX_COMPILE_DEFINITION "HAVE_PLEDGE")
1784         set(SANDBOX_FOUND ON)
1785     endif()
1786 endif()
1788 # Sandboxing: Landlock
1789 if(NOT SANDBOX_FOUND AND XZ_SANDBOX MATCHES "^auto$|^landlock$")
1790     # A compile check is done here because some systems have
1791     # linux/landlock.h, but do not have the syscalls defined
1792     # in order to actually use Linux Landlock.
1793     check_c_source_compiles("
1794             #include <linux/landlock.h>
1795             #include <sys/syscall.h>
1796             #include <sys/prctl.h>
1798             int main(void)
1799             {
1800                 (void)prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
1801                 (void)SYS_landlock_create_ruleset;
1802                 (void)SYS_landlock_restrict_self;
1803                 (void)LANDLOCK_CREATE_RULESET_VERSION;
1804                 return 0;
1805             }
1806         "
1807         HAVE_LINUX_LANDLOCK)
1809     if(HAVE_LINUX_LANDLOCK)
1810         set(SANDBOX_COMPILE_DEFINITION "HAVE_LINUX_LANDLOCK")
1811         set(SANDBOX_FOUND ON)
1813         # Of our three sandbox methods, only Landlock is incompatible
1814         # with -fsanitize. FreeBSD 13.2 with Capsicum was tested with
1815         # -fsanitize=address,undefined and had no issues. OpenBSD (as
1816         # of version 7.4) has minimal support for process instrumentation.
1817         # OpenBSD does not distribute the additional libraries needed
1818         # (libasan, libubsan, etc.) with GCC or Clang needed for runtime
1819         # sanitization support and instead only support
1820         # -fsanitize-minimal-runtime for minimal undefined behavior
1821         # sanitization. This minimal support is compatible with our use
1822         # of the Pledge sandbox. So only Landlock will result in a
1823         # build that cannot compress or decompress a single file to
1824         # standard out.
1825         if(CMAKE_C_FLAGS MATCHES "-fsanitize=")
1826             message(SEND_ERROR
1827                     "CMAKE_C_FLAGS or the environment variable CFLAGS "
1828                     "contains '-fsanitize=' which is incompatible "
1829                     "with Landlock sandboxing. Use -DXZ_SANDBOX=no "
1830                     "as an argument to 'cmake' when using '-fsanitize'.")
1831         endif()
1832     endif()
1833 endif()
1835 if(NOT SANDBOX_FOUND AND NOT XZ_SANDBOX MATCHES "^auto$|^no$")
1836     message(SEND_ERROR "XZ_SANDBOX=${XZ_SANDBOX} was used but "
1837                         "support for the sandboxing method wasn't found.")
1838 endif()
1841 #############################################################################
1842 # xzdec and lzmadec
1843 #############################################################################
1845 option(XZ_TOOL_XZDEC "Build and install the xzdec command line tool" ON)
1846 option(XZ_TOOL_LZMADEC "Build and install the lzmadec command line tool" ON)
1848 if(HAVE_DECODERS)
1849     set(XZDEC_TOOLS)
1851     if(XZ_TOOL_XZDEC)
1852         list(APPEND XZDEC_TOOLS xzdec)
1853     endif()
1855     if(XZ_TOOL_LZMADEC)
1856         list(APPEND XZDEC_TOOLS lzmadec)
1857     endif()
1859     foreach(XZDEC ${XZDEC_TOOLS})
1860         add_executable("${XZDEC}"
1861             src/common/sysdefs.h
1862             src/common/tuklib_common.h
1863             src/common/tuklib_config.h
1864             src/common/tuklib_exit.c
1865             src/common/tuklib_exit.h
1866             src/common/tuklib_gettext.h
1867             src/common/tuklib_progname.c
1868             src/common/tuklib_progname.h
1869             src/xzdec/xzdec.c
1870         )
1872         target_include_directories("${XZDEC}" PRIVATE
1873             src/common
1874             src/liblzma/api
1875         )
1877         target_link_libraries("${XZDEC}" PRIVATE liblzma libgnu)
1879         if(WIN32 OR CYGWIN)
1880             # Add the Windows resource file for xzdec.exe or lzmadec.exe.
1881             target_sources("${XZDEC}" PRIVATE "src/xzdec/${XZDEC}_w32res.rc")
1882             set_source_files_properties(
1883                 "src/xzdec/${XZDEC}_w32res.rc" PROPERTIES
1884                 OBJECT_DEPENDS "${W32RES_DEPENDENCIES}"
1885             )
1886         endif()
1888         if(SANDBOX_COMPILE_DEFINITION)
1889             target_compile_definitions("${XZDEC}" PRIVATE
1890                                        "${SANDBOX_COMPILE_DEFINITION}")
1891         endif()
1893         tuklib_progname("${XZDEC}")
1895         install(TARGETS "${XZDEC}"
1896                 RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1897                         COMPONENT "${XZDEC}_Runtime")
1898     endforeach()
1900     if(XZ_TOOL_LZMADEC)
1901         # This is the only build-time difference with lzmadec.
1902         target_compile_definitions(lzmadec PRIVATE "LZMADEC")
1903     endif()
1905     if(UNIX AND XZ_TOOL_XZDEC)
1906         # NOTE: This puts the lzmadec.1 symlinks into xzdec_Documentation.
1907         # This isn't great but doing them separately with translated
1908         # man pages would require extra code. So this has to suffice for now.
1909         #
1910         # Also, if xzdec is disabled but lzmadec isn't, then the man page
1911         # isn't installed at all. It could be done but it's not a typical
1912         # situation so let's keep this simpler.
1913         if(XZ_TOOL_LZMADEC)
1914             my_install_man(xzdec_Documentation src/xzdec/xzdec.1 lzmadec)
1915         else()
1916             my_install_man(xzdec_Documentation src/xzdec/xzdec.1 "")
1917         endif()
1918     endif()
1919 endif()
1922 #############################################################################
1923 # lzmainfo
1924 #############################################################################
1926 option(XZ_TOOL_LZMAINFO "Build and install the lzmainfo command line tool" ON)
1928 if(XZ_TOOL_LZMAINFO AND HAVE_DECODERS)
1929     add_executable(lzmainfo
1930         src/common/sysdefs.h
1931         src/common/tuklib_common.h
1932         src/common/tuklib_config.h
1933         src/common/tuklib_exit.c
1934         src/common/tuklib_exit.h
1935         src/common/tuklib_gettext.h
1936         src/common/tuklib_progname.c
1937         src/common/tuklib_progname.h
1938         src/lzmainfo/lzmainfo.c
1939     )
1941     target_include_directories(lzmainfo PRIVATE
1942         src/common
1943         src/liblzma/api
1944     )
1946     target_link_libraries(lzmainfo PRIVATE liblzma libgnu)
1948     if(WIN32 OR CYGWIN)
1949         # Add the Windows resource file for lzmainfo.exe.
1950         target_sources(lzmainfo PRIVATE src/lzmainfo/lzmainfo_w32res.rc)
1951         set_source_files_properties(src/lzmainfo/lzmainfo_w32res.rc PROPERTIES
1952             OBJECT_DEPENDS "${W32RES_DEPENDENCIES}"
1953         )
1954     endif()
1956     tuklib_progname(lzmainfo)
1958     # NOTE: The translations are in the "xz" domain and the .mo files are
1959     # installed as part of the "xz" target.
1960     if(XZ_NLS)
1961         target_link_libraries(lzmainfo PRIVATE Intl::Intl)
1963         target_compile_definitions(lzmainfo PRIVATE
1964                 ENABLE_NLS
1965                 PACKAGE="${TRANSLATION_DOMAIN}"
1966                 LOCALEDIR="${LOCALEDIR_DEFINITION}"
1967         )
1968     endif()
1970     install(TARGETS lzmainfo
1971             RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1972                     COMPONENT lzmainfo_Runtime)
1974     if(UNIX)
1975         my_install_man(lzmainfo_Documentation src/lzmainfo/lzmainfo.1 "")
1976     endif()
1977 endif()
1980 #############################################################################
1981 # xz
1982 #############################################################################
1984 option(XZ_TOOL_XZ "Build and install the xz command line tool" ON)
1986 if(XZ_TOOL_XZ)
1987     add_executable(xz
1988         src/common/mythread.h
1989         src/common/sysdefs.h
1990         src/common/tuklib_common.h
1991         src/common/tuklib_config.h
1992         src/common/tuklib_exit.c
1993         src/common/tuklib_exit.h
1994         src/common/tuklib_gettext.h
1995         src/common/tuklib_integer.h
1996         src/common/tuklib_mbstr.h
1997         src/common/tuklib_mbstr_fw.c
1998         src/common/tuklib_mbstr_width.c
1999         src/common/tuklib_open_stdxxx.c
2000         src/common/tuklib_open_stdxxx.h
2001         src/common/tuklib_progname.c
2002         src/common/tuklib_progname.h
2003         src/xz/args.c
2004         src/xz/args.h
2005         src/xz/coder.c
2006         src/xz/coder.h
2007         src/xz/file_io.c
2008         src/xz/file_io.h
2009         src/xz/hardware.c
2010         src/xz/hardware.h
2011         src/xz/main.c
2012         src/xz/main.h
2013         src/xz/message.c
2014         src/xz/message.h
2015         src/xz/mytime.c
2016         src/xz/mytime.h
2017         src/xz/options.c
2018         src/xz/options.h
2019         src/xz/private.h
2020         src/xz/sandbox.c
2021         src/xz/sandbox.h
2022         src/xz/signals.c
2023         src/xz/signals.h
2024         src/xz/suffix.c
2025         src/xz/suffix.h
2026         src/xz/util.c
2027         src/xz/util.h
2028     )
2030     target_include_directories(xz PRIVATE
2031         src/common
2032         src/liblzma/api
2033     )
2035     if(HAVE_DECODERS)
2036         target_sources(xz PRIVATE
2037             src/xz/list.c
2038             src/xz/list.h
2039         )
2040     endif()
2042     target_link_libraries(xz PRIVATE liblzma libgnu)
2044     if(USE_POSIX_THREADS)
2045         # src/xz/signals.c uses mythread_sigmask() which with POSIX
2046         # threads calls pthread_sigmask(). Thus, we need the threading
2047         # library as a dependency for xz. The liblzma target links against
2048         # Threads::Threads PRIVATEly, thus that won't provide the pthreads
2049         # symbols for xz.
2050         #
2051         # NOTE: The build may work without this if the symbol is in libc
2052         # but it is mandatory to have this here to keep it working with
2053         # all pthread implementations.
2054         target_link_libraries(xz PRIVATE Threads::Threads)
2055     endif()
2057     set(XZ_ASSUME_RAM "128" CACHE STRING "Assume that the system has \
2058 this many MiB of RAM if xz cannot determine the amount at runtime")
2059     target_compile_definitions(xz PRIVATE "ASSUME_RAM=${XZ_ASSUME_RAM}")
2061     if(WIN32 OR CYGWIN)
2062         # Add the Windows resource file for xz.exe.
2063         target_sources(xz PRIVATE src/xz/xz_w32res.rc)
2064         set_source_files_properties(src/xz/xz_w32res.rc PROPERTIES
2065             OBJECT_DEPENDS "${W32RES_DEPENDENCIES}"
2066         )
2067     endif()
2069     if(SANDBOX_COMPILE_DEFINITION)
2070         target_compile_definitions(xz PRIVATE "${SANDBOX_COMPILE_DEFINITION}")
2071     endif()
2073     tuklib_progname(xz)
2074     tuklib_mbstr(xz)
2076     check_symbol_exists(optreset getopt.h HAVE_OPTRESET)
2077     tuklib_add_definition_if(xz HAVE_OPTRESET)
2079     check_symbol_exists(posix_fadvise fcntl.h HAVE_POSIX_FADVISE)
2080     tuklib_add_definition_if(xz HAVE_POSIX_FADVISE)
2082     # How to get file time:
2083     check_struct_has_member("struct stat" st_atim.tv_nsec
2084                             "sys/types.h;sys/stat.h"
2085                             HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
2086     if(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
2087         tuklib_add_definitions(xz HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
2088     else()
2089         check_struct_has_member("struct stat" st_atimespec.tv_nsec
2090                                 "sys/types.h;sys/stat.h"
2091                                 HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
2092         if(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
2093             tuklib_add_definitions(xz HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
2094         else()
2095             check_struct_has_member("struct stat" st_atimensec
2096                                     "sys/types.h;sys/stat.h"
2097                                     HAVE_STRUCT_STAT_ST_ATIMENSEC)
2098             tuklib_add_definition_if(xz HAVE_STRUCT_STAT_ST_ATIMENSEC)
2099         endif()
2100     endif()
2102     # How to set file time:
2103     check_symbol_exists(futimens "sys/types.h;sys/stat.h" HAVE_FUTIMENS)
2104     if(HAVE_FUTIMENS)
2105         tuklib_add_definitions(xz HAVE_FUTIMENS)
2106     else()
2107         check_symbol_exists(futimes "sys/time.h" HAVE_FUTIMES)
2108         if(HAVE_FUTIMES)
2109             tuklib_add_definitions(xz HAVE_FUTIMES)
2110         else()
2111             check_symbol_exists(futimesat "sys/time.h" HAVE_FUTIMESAT)
2112             if(HAVE_FUTIMESAT)
2113                 tuklib_add_definitions(xz HAVE_FUTIMESAT)
2114             else()
2115                 check_symbol_exists(utimes "sys/time.h" HAVE_UTIMES)
2116                 if(HAVE_UTIMES)
2117                     tuklib_add_definitions(xz HAVE_UTIMES)
2118                 else()
2119                     check_symbol_exists(_futime "sys/utime.h" HAVE__FUTIME)
2120                     if(HAVE__FUTIME)
2121                         tuklib_add_definitions(xz HAVE__FUTIME)
2122                     else()
2123                         check_symbol_exists(utime "utime.h" HAVE_UTIME)
2124                         tuklib_add_definition_if(xz HAVE_UTIME)
2125                     endif()
2126                 endif()
2127             endif()
2128         endif()
2129     endif()
2131     if(XZ_NLS)
2132         target_link_libraries(xz PRIVATE Intl::Intl)
2134         target_compile_definitions(xz PRIVATE
2135                 ENABLE_NLS
2136                 PACKAGE="${TRANSLATION_DOMAIN}"
2137                 LOCALEDIR="${LOCALEDIR_DEFINITION}"
2138         )
2140         file(STRINGS po/LINGUAS LINGUAS)
2142         # NOTE: gettext_process_po_files' INSTALL_DESTINATION is
2143         # incompatible with how Autotools requires the .po files to
2144         # be named. CMake would require each .po file to be named with
2145         # the translation domain and thus each .po file would need its
2146         # own language-specific directory (like "po/fi/xz.po"). On top
2147         # of this, INSTALL_DESTINATION doesn't allow specifying COMPONENT
2148         # and thus the .mo files go into "Unspecified" component. So we
2149         # can use gettext_process_po_files to convert the .po files but
2150         # installation needs to be done with our own code.
2151         #
2152         # Also, the .gmo files will go to root of the build directory
2153         # instead of neatly into a subdirectory. This is hardcoded in
2154         # CMake's FindGettext.cmake.
2155         foreach(LANG IN LISTS LINGUAS)
2156             gettext_process_po_files("${LANG}" ALL
2157                     PO_FILES "${CMAKE_CURRENT_SOURCE_DIR}/po/${LANG}.po")
2158         endforeach()
2160         foreach(LANG IN LISTS LINGUAS)
2161             install(
2162                 FILES "${CMAKE_CURRENT_BINARY_DIR}/${LANG}.gmo"
2163                 DESTINATION "${CMAKE_INSTALL_LOCALEDIR}/${LANG}/LC_MESSAGES"
2164                 RENAME "${TRANSLATION_DOMAIN}.mo"
2165                 COMPONENT xz_Runtime)
2166         endforeach()
2167     endif()
2169     # This command must be before the symlink creation to keep things working
2170     # on Cygwin and MSYS2 in all cases.
2171     #
2172     #   - Cygwin can encode symlinks in multiple ways. This can be
2173     #     controlled via the environment variable "CYGWIN". If it contains
2174     #     "winsymlinks:nativestrict" then symlink creation will fail if
2175     #     the link target doesn't exist. This mode isn't the default though.
2176     #     See: https://cygwin.com/faq.html#faq.api.symlinks
2177     #
2178     #   - MSYS2 supports the same winsymlinks option in the environment
2179     #     variable "MSYS" (not "MSYS2). The default in MSYS2 is to make
2180     #     a copy of the file instead of any kind of symlink. Thus the link
2181     #     target must exist or the creation of the "symlink" (copy) will fail.
2182     #
2183     # Our installation order must be such that when a symbolic link is created
2184     # its target must already exists. There is no race condition for parallel
2185     # builds because the generated cmake_install.cmake executes serially.
2186     install(TARGETS xz
2187             RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
2188                     COMPONENT xz_Runtime)
2190     if(UNIX)
2191         option(XZ_TOOL_SYMLINKS "Create unxz and xzcat symlinks" ON)
2192         option(XZ_TOOL_SYMLINKS_LZMA
2193                "Create 'lzma' and other symlinks for LZMA Utils compatibility"
2194                ON)
2195         set(XZ_LINKS)
2197         if(XZ_TOOL_SYMLINKS)
2198             list(APPEND XZ_LINKS "unxz" "xzcat")
2199         endif()
2201         if(XZ_TOOL_SYMLINKS_LZMA)
2202             list(APPEND XZ_LINKS "lzma" "unlzma" "lzcat")
2203         endif()
2205         # On Cygwin, don't add the .exe suffix to the symlinks.
2206         #
2207         # FIXME? Does this make sense on MSYS & MSYS2 where "ln -s"
2208         # by default makes copies? Inside MSYS & MSYS2 it is possible
2209         # to execute files without the .exe suffix but not outside
2210         # (like in Command Prompt). Omitting the suffix matches
2211         # what configure.ac has done for many years though.
2212         my_install_symlinks(xz_Runtime "${CMAKE_INSTALL_BINDIR}"
2213                             "xz${CMAKE_EXECUTABLE_SUFFIX}" "" "${XZ_LINKS}")
2215         # Install the man pages and (optionally) their symlinks
2216         # and translations.
2217         my_install_man(xz_Documentation src/xz/xz.1 "${XZ_LINKS}")
2218     endif()
2219 endif()
2222 #############################################################################
2223 # Scripts
2224 #############################################################################
2226 set(ENABLE_SCRIPTS OFF)
2228 if(UNIX)
2229     # NOTE: These depend on the xz tool and decoder support.
2230     option(XZ_TOOL_SCRIPTS "Install the scripts \
2231 xzdiff, xzgrep, xzmore, xzless, and their symlinks" ON)
2233     if(XZ_TOOL_SCRIPTS AND XZ_TOOL_XZ AND HAVE_DECODERS)
2234         set(ENABLE_SCRIPTS ON)
2235     endif()
2237     # NOTE: This isn't as sophisticated as in the Autotools build which
2238     # uses posix-shell.m4 but hopefully this doesn't need to be either.
2239     # CMake likely won't be used on as many (old) obscure systems as the
2240     # Autotools-based builds are.
2241     if(CMAKE_SYSTEM_NAME STREQUAL "SunOS" AND EXISTS "/usr/xpg4/bin/sh")
2242         set(POSIX_SHELL_DEFAULT "/usr/xpg4/bin/sh")
2243     else()
2244         set(POSIX_SHELL_DEFAULT "/bin/sh")
2245     endif()
2247     set(XZ_POSIX_SHELL "${POSIX_SHELL_DEFAULT}" CACHE STRING
2248         "Shell to use for scripts (xzgrep and others)")
2250     # Guess the extra path to add from XZ_POSIX_SHELL. Autotools-based build
2251     # has a separate option --enable-path-for-scripts=PREFIX but this is
2252     # enough for Solaris.
2253     set(enable_path_for_scripts)
2254     get_filename_component(POSIX_SHELL_DIR "${XZ_POSIX_SHELL}" DIRECTORY)
2256     if(NOT POSIX_SHELL_DIR MATCHES "^/bin$|^/usr/bin$")
2257         set(enable_path_for_scripts "PATH=${POSIX_SHELL_DIR}:\$PATH")
2258     endif()
2260     set(XZDIFF_LINKS xzcmp)
2261     set(XZGREP_LINKS xzegrep xzfgrep)
2262     set(XZMORE_LINKS)
2263     set(XZLESS_LINKS)
2265     if(XZ_TOOL_SYMLINKS_LZMA)
2266         list(APPEND XZDIFF_LINKS lzdiff lzcmp)
2267         list(APPEND XZGREP_LINKS lzgrep lzegrep lzfgrep)
2268         list(APPEND XZMORE_LINKS lzmore)
2269         list(APPEND XZLESS_LINKS lzless)
2270     endif()
2272     set(xz "xz")
2273     set(POSIX_SHELL "${XZ_POSIX_SHELL}")
2275     foreach(S xzdiff xzgrep xzmore xzless)
2276         configure_file("src/scripts/${S}.in" "${S}"
2277                @ONLY
2278                NEWLINE_STYLE LF
2279                FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE
2280                                 GROUP_READ GROUP_EXECUTE
2281                                 WORLD_READ WORLD_EXECUTE)
2283         if(ENABLE_SCRIPTS)
2284             install(PROGRAMS "${CMAKE_CURRENT_BINARY_DIR}/${S}"
2285                     DESTINATION "${CMAKE_INSTALL_BINDIR}"
2286                     COMPONENT scripts_Runtime)
2287         endif()
2288     endforeach()
2290     unset(xz)
2291     unset(POSIX_SHELL)
2292     unset(enable_path_for_scripts)
2294     if(ENABLE_SCRIPTS)
2295         my_install_symlinks(scripts_Runtime "${CMAKE_INSTALL_BINDIR}"
2296                             xzdiff "" "${XZDIFF_LINKS}")
2298         my_install_symlinks(scripts_Runtime "${CMAKE_INSTALL_BINDIR}"
2299                             xzgrep "" "${XZGREP_LINKS}")
2301         my_install_symlinks(scripts_Runtime "${CMAKE_INSTALL_BINDIR}"
2302                             xzmore "" "${XZMORE_LINKS}")
2304         my_install_symlinks(scripts_Runtime "${CMAKE_INSTALL_BINDIR}"
2305                             xzless "" "${XZLESS_LINKS}")
2307         my_install_man(scripts_Documentation
2308                        src/scripts/xzdiff.1 "${XZDIFF_LINKS}")
2310         my_install_man(scripts_Documentation
2311                        src/scripts/xzgrep.1 "${XZGREP_LINKS}")
2313         my_install_man(scripts_Documentation
2314                        src/scripts/xzmore.1 "${XZMORE_LINKS}")
2316         my_install_man(scripts_Documentation
2317                        src/scripts/xzless.1 "${XZLESS_LINKS}")
2318     endif()
2319 endif()
2322 #############################################################################
2323 # Documentation
2324 #############################################################################
2326 if(UNIX)
2327     option(XZ_DOXYGEN "Use Doxygen to generate liblzma API docs" OFF)
2329     if (XZ_DOXYGEN)
2330         file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/doc")
2332         add_custom_command(
2333             VERBATIM
2334             COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/doxygen/update-doxygen"
2335             ARGS "api"
2336                  "${CMAKE_CURRENT_SOURCE_DIR}"
2337                  "${CMAKE_CURRENT_BINARY_DIR}/doc"
2338             OUTPUT doc/api/index.html
2339             DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/doxygen/update-doxygen"
2340                     "${CMAKE_CURRENT_SOURCE_DIR}/doxygen/Doxyfile"
2341                     ${LIBLZMA_API_HEADERS}
2342         )
2344         add_custom_target(
2345             liblzma-doc-api ALL
2346             DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/doc/api/index.html"
2347         )
2349         install(DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/doc/api"
2350                 DESTINATION "${CMAKE_INSTALL_DOCDIR}"
2351                 COMPONENT liblzma_Documentation)
2352     endif()
2353 endif()
2355 option(XZ_DOC "Install basic documentation, examples, and license files" ON)
2356 if(XZ_DOC)
2357     install(DIRECTORY doc/examples
2358             DESTINATION "${CMAKE_INSTALL_DOCDIR}"
2359             COMPONENT liblzma_Documentation)
2361     # GPLv2 applies to the scripts. If GNU getopt_long is used then
2362     # LGPLv2.1 applies to the command line tools but, using the
2363     # section 3 of LGPLv2.1, GNU getopt_long can be handled as GPLv2 too.
2364     # Thus GPLv2 should be enough here.
2365     install(FILES AUTHORS
2366                   COPYING
2367                   COPYING.0BSD
2368                   COPYING.GPLv2
2369                   NEWS
2370                   README
2371                   THANKS
2372                   doc/faq.txt
2373                   doc/history.txt
2374                   doc/lzma-file-format.txt
2375                   doc/xz-file-format.txt
2376             DESTINATION "${CMAKE_INSTALL_DOCDIR}"
2377             COMPONENT Documentation)
2378 endif()
2381 #############################################################################
2382 # Tests
2383 #############################################################################
2385 # Tests are in a separate file so that it's possible to delete the whole
2386 # "tests" directory and still have a working build, just without the tests.
2387 include(tests/tests.cmake OPTIONAL)