Build: Fix ARM64 CRC32 instruction feature test.
[xz.git] / CMakeLists.txt
blob06282b4d6257ea241e7a2ca51d5dbe52f37c2cef
1 # SPDX-License-Identifier: 0BSD
3 #############################################################################
5 # CMake support for building XZ Utils
7 # The complete CMake-based build hasn't been tested much yet and
8 # thus it's still slightly experimental. Testing this especially
9 # outside GNU/Linux and Windows would be great now.
11 # A few things are still missing compared to the Autotools-based build:
13 #   - A few tests aren't CMake compatible yet and thus aren't run!
15 #   - 32-bit x86 assembly code for CRC32 and CRC64 isn't used.
17 #   - External SHA-256 code isn't supported but it's disabled by
18 #     default in the Autotools build too (--enable-external-sha256).
20 #   - Extra compiler warning flags aren't added by default.
22 # About CMAKE_BUILD_TYPE:
24 #   - CMake's standard choices are fine to use for production builds,
25 #     including "Release" and "RelWithDebInfo".
27 #     NOTE: While "Release" uses -O3 by default with some compilers,
28 #     this file overrides -O3 to -O2 for "Release" builds if
29 #     CMAKE_C_FLAGS_RELEASE is not defined by the user. At least
30 #     with GCC and Clang/LLVM, -O3 doesn't seem useful for this
31 #     package as it can result in bigger binaries without any
32 #     improvement in speed compared to -O2.
34 #   - Empty value (the default) is handled slightly specially: It
35 #     adds -DNDEBUG to disable debugging code (assert() and a few
36 #     other things). No optimization flags are added so an empty
37 #     CMAKE_BUILD_TYPE is an easy way to build with whatever
38 #     optimization flags one wants, and so this method is also
39 #     suitable for production builds.
41 #     If debugging is wanted when using empty CMAKE_BUILD_TYPE,
42 #     include -UNDEBUG in the CFLAGS environment variable or
43 #     in the CMAKE_C_FLAGS CMake variable to override -DNDEBUG.
44 #     With empty CMAKE_BUILD_TYPE, the -UNDEBUG option will go
45 #     after the -DNDEBUG option on the compiler command line and
46 #     thus NDEBUG will be undefined.
48 #   - Non-standard build types like "None" aren't treated specially
49 #     and thus won't have -DNEBUG. Such non-standard build types
50 #     SHOULD BE AVOIDED FOR PRODUCTION BUILDS. Or at least one
51 #     should remember to add -DNDEBUG.
53 # If building from xz.git instead of a release tarball, consider
54 # the following *before* running cmake:
56 #   - To get translated messages, install GNU gettext tools (the
57 #     command msgfmt is needed). Alternatively disable translations
58 #     by setting ENABLE_NLS=OFF.
60 #   - To get translated man pages, run po4a/update-po which requires
61 #     the po4a tool. The build works without this step too.
63 #   - To get Doxygen-generated liblzma API docs in HTML format,
64 #     run doxygen/update-doxygen which requires the doxygen tool.
65 #     The build works without this step too.
67 # This file provides the following installation components (if you only
68 # need liblzma, install only its components!):
69 #   - liblzma_Runtime (shared library only)
70 #   - liblzma_Development
71 #   - liblzma_Documentation (examples and Doxygen-generated API docs as HTML)
72 #   - xz_Runtime (xz, the symlinks, and possibly translation files)
73 #   - xz_Documentation (xz man pages and the symlinks)
74 #   - xzdec_Runtime
75 #   - xzdec_Documentation (xzdec *and* lzmadec man pages)
76 #   - lzmadec_Runtime
77 #   - lzmainfo_Runtime
78 #   - lzmainfo_Documentation (lzmainfo man pages)
79 #   - scripts_Runtime (xzdiff, xzgrep, xzless, xzmore)
80 #   - scripts_Documentation (their man pages)
81 #   - Documentation (generic docs like README and licenses)
83 # To find the target liblzma::liblzma from other packages, use the CONFIG
84 # option with find_package() to avoid a conflict with the FindLibLZMA module
85 # with case-insensitive file systems. For example, to require liblzma 5.2.5
86 # or a newer compatible version:
88 #     find_package(liblzma 5.2.5 REQUIRED CONFIG)
89 #     target_link_libraries(my_application liblzma::liblzma)
91 #############################################################################
93 # Author: Lasse Collin
95 #############################################################################
97 # NOTE: Translation support is disabled with CMake older than 3.20.
98 cmake_minimum_required(VERSION 3.14...3.28 FATAL_ERROR)
100 include(CMakePushCheckState)
101 include(CheckIncludeFile)
102 include(CheckSymbolExists)
103 include(CheckStructHasMember)
104 include(CheckCSourceCompiles)
105 include(cmake/tuklib_large_file_support.cmake)
106 include(cmake/tuklib_integer.cmake)
107 include(cmake/tuklib_cpucores.cmake)
108 include(cmake/tuklib_physmem.cmake)
109 include(cmake/tuklib_progname.cmake)
110 include(cmake/tuklib_mbstr.cmake)
112 set(PACKAGE_NAME "XZ Utils")
113 set(PACKAGE_BUGREPORT "xz@tukaani.org")
114 set(PACKAGE_URL "https://xz.tukaani.org/xz-utils/")
116 # Get the package version from version.h into PACKAGE_VERSION variable.
117 file(READ src/liblzma/api/lzma/version.h PACKAGE_VERSION)
118 string(REGEX REPLACE
119 "^.*\n\
120 #define LZMA_VERSION_MAJOR ([0-9]+)\n\
122 #define LZMA_VERSION_MINOR ([0-9]+)\n\
124 #define LZMA_VERSION_PATCH ([0-9]+)\n\
125 .*$"
126        "\\1.\\2.\\3" PACKAGE_VERSION "${PACKAGE_VERSION}")
128 # With several compilers, CMAKE_BUILD_TYPE=Release uses -O3 optimization
129 # which results in bigger code without a clear difference in speed. If
130 # no user-defined CMAKE_C_FLAGS_RELEASE is present, override -O3 to -O2
131 # to make it possible to recommend CMAKE_BUILD_TYPE=Release.
132 if(NOT DEFINED CMAKE_C_FLAGS_RELEASE)
133     set(OVERRIDE_O3_IN_C_FLAGS_RELEASE ON)
134 endif()
136 # Among other things, this gives us variables xz_VERSION and xz_VERSION_MAJOR.
137 project(xz VERSION "${PACKAGE_VERSION}" LANGUAGES C)
139 if(OVERRIDE_O3_IN_C_FLAGS_RELEASE)
140     # Looking at CMake's source, there aren't any _FLAGS_RELEASE_INIT
141     # entries where "-O3" would appear as part of some other option,
142     # thus a simple search and replace should be fine.
143     string(REPLACE -O3 -O2 CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}")
145     # Update the cache value while keeping its docstring unchanged.
146     set_property(CACHE CMAKE_C_FLAGS_RELEASE
147                  PROPERTY VALUE "${CMAKE_C_FLAGS_RELEASE}")
148 endif()
150 # We need a compiler that supports enough C99 or newer (variable-length arrays
151 # aren't needed, those are optional in C17). Setting CMAKE_C_STANDARD here
152 # makes it the default for all targets. It doesn't affect the INTERFACE so
153 # liblzma::liblzma won't end up with INTERFACE_COMPILE_FEATURES "c_std_99"
154 # (the API headers are C89 and C++ compatible).
155 set(CMAKE_C_STANDARD 99)
156 set(CMAKE_C_STANDARD_REQUIRED ON)
158 # On Apple OSes, don't build executables as bundles:
159 set(CMAKE_MACOSX_BUNDLE OFF)
161 # Set CMAKE_INSTALL_LIBDIR and friends. This needs to be done before
162 # the LOCALEDIR_DEFINITION workaround below.
163 include(GNUInstallDirs)
165 # windres from GNU binutils can be tricky with command line arguments
166 # that contain spaces or other funny characters. Unfortunately we need
167 # a space in PACKAGE_NAME. Using \x20 to encode the US-ASCII space seems
168 # to work in both cmd.exe and /bin/sh.
170 # However, even \x20 isn't enough in all situations, resulting in
171 # "syntax error" from windres. Using --use-temp-file prevents windres
172 # from using popen() and this seems to fix the problem.
174 # llvm-windres from Clang/LLVM 16.0.6 and older: The \x20 results
175 # in "XZx20Utils" in the compiled binary. The option --use-temp-file
176 # makes no difference.
178 # llvm-windres 17.0.0 and later: It emulates GNU windres more accurately, so
179 # the workarounds used with GNU windres must be used with llvm-windres too.
181 # CMake 3.27 doesn't have CMAKE_RC_COMPILER_ID so we rely on
182 # CMAKE_C_COMPILER_ID.
183 if((MINGW OR CYGWIN OR MSYS) AND (
184         NOT CMAKE_C_COMPILER_ID STREQUAL "Clang" OR
185         CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL "17"))
186     # Use workarounds with GNU windres and llvm-windres >= 17.0.0. The \x20
187     # in PACKAGE_NAME_DEFINITION works with gcc and clang too so we don't need
188     # to worry how to pass different flags to windres and the C compiler.
189     # Keep the original PACKAGE_NAME intact for generation of liblzma.pc.
190     string(APPEND CMAKE_RC_FLAGS " --use-temp-file")
191     string(REPLACE " " "\\x20" PACKAGE_NAME_DEFINITION "${PACKAGE_NAME}")
193     # Use octal because "Program Files" would become \x20F.
194     string(REPLACE " " "\\040" LOCALEDIR_DEFINITION
195            "${CMAKE_INSTALL_FULL_LOCALEDIR}")
196 else()
197     # Elsewhere a space is safe. This also keeps things compatible with
198     # EBCDIC in case CMake-based build is ever done on such a system.
199     set(PACKAGE_NAME_DEFINITION "${PACKAGE_NAME}")
200     set(LOCALEDIR_DEFINITION "${CMAKE_INSTALL_FULL_LOCALEDIR}")
201 endif()
203 # Definitions common to all targets:
204 add_compile_definitions(
205     # Package info:
206     PACKAGE_NAME="${PACKAGE_NAME_DEFINITION}"
207     PACKAGE_BUGREPORT="${PACKAGE_BUGREPORT}"
208     PACKAGE_URL="${PACKAGE_URL}"
210     # Standard headers and types are available:
211     HAVE_STDBOOL_H
212     HAVE__BOOL
213     HAVE_STDINT_H
214     HAVE_INTTYPES_H
216     # Always enable CRC32 since liblzma should never build without it.
217     HAVE_CHECK_CRC32
219     # Disable assert() checks when no build type has been specified. Non-empty
220     # build types like "Release" and "Debug" handle this by default.
221     $<$<CONFIG:>:NDEBUG>
225 ######################
226 # System definitions #
227 ######################
229 # _GNU_SOURCE and such definitions. This specific macro is special since
230 # it also adds the definitions to CMAKE_REQUIRED_DEFINITIONS.
231 tuklib_use_system_extensions(ALL)
233 # Check for large file support. It's required on some 32-bit platforms and
234 # even on 64-bit MinGW-w64 to get 64-bit off_t. This can be forced off on
235 # the CMake command line if needed: -DLARGE_FILE_SUPPORT=OFF
236 tuklib_large_file_support(ALL)
238 # This is needed by liblzma and xz.
239 tuklib_integer(ALL)
241 # This is used for liblzma.pc generation to add -lrt if needed.
242 set(LIBS)
244 # Check for clock_gettime(). Do this before checking for threading so
245 # that we know there if CLOCK_MONOTONIC is available.
246 check_symbol_exists(clock_gettime time.h HAVE_CLOCK_GETTIME)
248 if(NOT HAVE_CLOCK_GETTIME)
249     # With glibc <= 2.17 or Solaris 10 this needs librt.
250     # Add librt for the next check for HAVE_CLOCK_GETTIME. If it is
251     # found after including the library, we know that librt is required.
252     list(INSERT CMAKE_REQUIRED_LIBRARIES 0 rt)
253     check_symbol_exists(clock_gettime time.h HAVE_CLOCK_GETTIME_LIBRT)
255     # If it was found now, add librt to all targets and keep it in
256     # CMAKE_REQUIRED_LIBRARIES for further tests too.
257     if(HAVE_CLOCK_GETTIME_LIBRT)
258         link_libraries(rt)
259         set(LIBS "-lrt") # For liblzma.pc
260     else()
261         list(REMOVE_AT CMAKE_REQUIRED_LIBRARIES 0)
262     endif()
263 endif()
265 if(HAVE_CLOCK_GETTIME OR HAVE_CLOCK_GETTIME_LIBRT)
266     add_compile_definitions(HAVE_CLOCK_GETTIME)
268     # Check if CLOCK_MONOTONIC is available for clock_gettime().
269     check_symbol_exists(CLOCK_MONOTONIC time.h HAVE_CLOCK_MONOTONIC)
270     tuklib_add_definition_if(ALL HAVE_CLOCK_MONOTONIC)
271 endif()
273 # Translation support requires CMake 3.20 because it added the Intl::Intl
274 # target so we don't need to play with the individual variables.
276 # The defintion ENABLE_NLS is added only to those targets that use it, thus
277 # it's not done here. (xz has translations, xzdec doesn't.)
278 if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.20")
279     find_package(Intl)
280     find_package(Gettext)
281     if(Intl_FOUND)
282         option(ENABLE_NLS "Native Language Support (translated messages)" ON)
284         # The *installed* name of the translation files is "xz.mo".
285         set(TRANSLATION_DOMAIN "xz")
286     endif()
287 endif()
289 # Options for new enough GCC or Clang on any arch or operating system:
290 if(CMAKE_C_COMPILER_ID MATCHES GNU|Clang)
291     # configure.ac has a long list but it won't be copied here:
292     add_compile_options(-Wall -Wextra)
293 endif()
296 #############################################################################
297 # liblzma
298 #############################################################################
300 option(BUILD_SHARED_LIBS "Build liblzma as a shared library instead of static")
302 add_library(liblzma
303     src/common/mythread.h
304     src/common/sysdefs.h
305     src/common/tuklib_common.h
306     src/common/tuklib_config.h
307     src/common/tuklib_integer.h
308     src/common/tuklib_physmem.c
309     src/common/tuklib_physmem.h
310     src/liblzma/api/lzma.h
311     src/liblzma/api/lzma/base.h
312     src/liblzma/api/lzma/bcj.h
313     src/liblzma/api/lzma/block.h
314     src/liblzma/api/lzma/check.h
315     src/liblzma/api/lzma/container.h
316     src/liblzma/api/lzma/delta.h
317     src/liblzma/api/lzma/filter.h
318     src/liblzma/api/lzma/hardware.h
319     src/liblzma/api/lzma/index.h
320     src/liblzma/api/lzma/index_hash.h
321     src/liblzma/api/lzma/lzma12.h
322     src/liblzma/api/lzma/stream_flags.h
323     src/liblzma/api/lzma/version.h
324     src/liblzma/api/lzma/vli.h
325     src/liblzma/check/check.c
326     src/liblzma/check/check.h
327     src/liblzma/check/crc_common.h
328     src/liblzma/check/crc_x86_clmul.h
329     src/liblzma/check/crc32_arm64.h
330     src/liblzma/common/block_util.c
331     src/liblzma/common/common.c
332     src/liblzma/common/common.h
333     src/liblzma/common/easy_preset.c
334     src/liblzma/common/easy_preset.h
335     src/liblzma/common/filter_common.c
336     src/liblzma/common/filter_common.h
337     src/liblzma/common/hardware_physmem.c
338     src/liblzma/common/index.c
339     src/liblzma/common/index.h
340     src/liblzma/common/memcmplen.h
341     src/liblzma/common/stream_flags_common.c
342     src/liblzma/common/stream_flags_common.h
343     src/liblzma/common/string_conversion.c
344     src/liblzma/common/vli_size.c
347 target_include_directories(liblzma PRIVATE
348     src/liblzma/api
349     src/liblzma/common
350     src/liblzma/check
351     src/liblzma/lz
352     src/liblzma/rangecoder
353     src/liblzma/lzma
354     src/liblzma/delta
355     src/liblzma/simple
356     src/common
360 ######################
361 # Size optimizations #
362 ######################
364 option(ENABLE_SMALL "Reduce code size at expense of speed. \
365 This may be useful together with CMAKE_BUILD_TYPE=MinSizeRel.")
367 if(ENABLE_SMALL)
368     add_compile_definitions(HAVE_SMALL)
369 endif()
372 ##########
373 # Checks #
374 ##########
376 set(ADDITIONAL_SUPPORTED_CHECKS crc64 sha256)
378 set(ADDITIONAL_CHECK_TYPES "${ADDITIONAL_SUPPORTED_CHECKS}" CACHE STRING
379     "Additional check types to support (crc32 is always built)")
381 foreach(CHECK IN LISTS ADDITIONAL_CHECK_TYPES)
382     if(NOT CHECK IN_LIST ADDITIONAL_SUPPORTED_CHECKS)
383         message(FATAL_ERROR "'${CHECK}' is not a supported check type")
384     endif()
385 endforeach()
387 if(ENABLE_SMALL)
388     target_sources(liblzma PRIVATE src/liblzma/check/crc32_small.c)
389 else()
390     target_sources(liblzma PRIVATE
391         src/liblzma/check/crc32_fast.c
392         src/liblzma/check/crc32_table.c
393         src/liblzma/check/crc32_table_be.h
394         src/liblzma/check/crc32_table_le.h
395     )
396 endif()
398 if("crc64" IN_LIST ADDITIONAL_CHECK_TYPES)
399     add_compile_definitions("HAVE_CHECK_CRC64")
401     if(ENABLE_SMALL)
402         target_sources(liblzma PRIVATE src/liblzma/check/crc64_small.c)
403     else()
404         target_sources(liblzma PRIVATE
405             src/liblzma/check/crc64_fast.c
406             src/liblzma/check/crc64_table.c
407             src/liblzma/check/crc64_table_be.h
408             src/liblzma/check/crc64_table_le.h
409         )
410     endif()
411 endif()
413 if("sha256" IN_LIST ADDITIONAL_CHECK_TYPES)
414     add_compile_definitions("HAVE_CHECK_SHA256")
415     target_sources(liblzma PRIVATE src/liblzma/check/sha256.c)
416 endif()
419 #################
420 # Match finders #
421 #################
423 set(SUPPORTED_MATCH_FINDERS hc3 hc4 bt2 bt3 bt4)
425 set(MATCH_FINDERS "${SUPPORTED_MATCH_FINDERS}" CACHE STRING
426     "Match finders to support (at least one is required for LZMA1 or LZMA2)")
428 foreach(MF IN LISTS MATCH_FINDERS)
429     if(MF IN_LIST SUPPORTED_MATCH_FINDERS)
430         string(TOUPPER "${MF}" MF_UPPER)
431         add_compile_definitions("HAVE_MF_${MF_UPPER}")
432     else()
433         message(FATAL_ERROR "'${MF}' is not a supported match finder")
434     endif()
435 endforeach()
438 #############
439 # Threading #
440 #############
442 # Supported threading methods:
443 # ON    - autodetect the best threading method. The autodetection will
444 #         prefer Windows threading (win95 or vista) over posix if both are
445 #         available. vista threads will be used over win95 unless it is a
446 #         32-bit build.
447 # OFF   - Disable threading.
448 # posix - Use posix threading (pthreads), or throw an error if not available.
449 # win95 - Use Windows win95 threading, or throw an error if not available.
450 # vista - Use Windows vista threading, or throw an error if not available.
451 set(SUPPORTED_THREADING_METHODS ON OFF posix win95 vista)
453 set(ENABLE_THREADS ON CACHE STRING
454     "Threading method: Set to 'ON' to autodetect, 'OFF' to disable threading.")
456 # Create dropdown in CMake GUI since only 1 threading method is possible
457 # to select in a build.
458 set_property(CACHE ENABLE_THREADS
459              PROPERTY STRINGS "${SUPPORTED_THREADING_METHODS}")
461 # This is a flag variable set when win95 threads are used. We must ensure
462 # the combination of enable_small and win95 threads is not used without a
463 # compiler supporting attribute __constructor__.
464 set(USE_WIN95_THREADS OFF)
466 # This is a flag variable set when posix threads (pthreads) are used.
467 # It's needed when creating liblzma-config.cmake where dependency on
468 # Threads::Threads is only needed with pthreads.
469 set(USE_POSIX_THREADS OFF)
471 if(NOT ENABLE_THREADS IN_LIST SUPPORTED_THREADING_METHODS)
472     message(FATAL_ERROR "'${ENABLE_THREADS}' is not a supported "
473                         "threading method")
474 endif()
476 if(ENABLE_THREADS)
477     # Also set THREADS_PREFER_PTHREAD_FLAG since the flag has no effect
478     # for Windows threading.
479     set(THREADS_PREFER_PTHREAD_FLAG TRUE)
480     find_package(Threads REQUIRED)
482     # If both Windows and posix threading are available, prefer Windows.
483     # Note that on Cygwin CMAKE_USE_WIN32_THREADS_INIT is false.
484     if(CMAKE_USE_WIN32_THREADS_INIT AND NOT ENABLE_THREADS STREQUAL "posix")
485         if(ENABLE_THREADS STREQUAL "win95"
486                 OR (ENABLE_THREADS STREQUAL "ON"
487                     AND CMAKE_SIZEOF_VOID_P EQUAL 4))
488             # Use Windows 95 (and thus XP) compatible threads.
489             # This avoids use of features that were added in
490             # Windows Vista. This is used for 32-bit x86 builds for
491             # compatibility reasons since it makes no measurable difference
492             # in performance compared to Vista threads.
493             set(USE_WIN95_THREADS ON)
494             add_compile_definitions(MYTHREAD_WIN95)
495         else()
496             add_compile_definitions(MYTHREAD_VISTA)
497         endif()
498     elseif(CMAKE_USE_PTHREADS_INIT)
499         if(ENABLE_THREADS STREQUAL "posix" OR ENABLE_THREADS STREQUAL "ON")
500             # The threading library only needs to be explicitly linked
501             # for posix threads, so this is needed for creating
502             # liblzma-config.cmake later.
503             set(USE_POSIX_THREADS ON)
505             target_link_libraries(liblzma Threads::Threads)
506             add_compile_definitions(MYTHREAD_POSIX)
508             # Check if pthread_condattr_setclock() exists to
509             # use CLOCK_MONOTONIC.
510             if(HAVE_CLOCK_MONOTONIC)
511                 list(INSERT CMAKE_REQUIRED_LIBRARIES 0
512                      "${CMAKE_THREAD_LIBS_INIT}")
513                 check_symbol_exists(pthread_condattr_setclock pthread.h
514                                     HAVE_PTHREAD_CONDATTR_SETCLOCK)
515                 tuklib_add_definition_if(ALL HAVE_PTHREAD_CONDATTR_SETCLOCK)
516             endif()
517         else()
518             message(SEND_ERROR
519                     "Windows threading method was requested but a compatible "
520                     "library could not be found")
521         endif()
522     else()
523         message(SEND_ERROR "No supported threading library found")
524     endif()
526     target_sources(liblzma PRIVATE
527         src/common/tuklib_cpucores.c
528         src/common/tuklib_cpucores.h
529         src/liblzma/common/hardware_cputhreads.c
530         src/liblzma/common/outqueue.c
531         src/liblzma/common/outqueue.h
532     )
533 endif()
536 ############
537 # Encoders #
538 ############
540 set(SIMPLE_FILTERS
541     x86
542     arm
543     armthumb
544     arm64
545     powerpc
546     ia64
547     sparc
548     riscv
551 # The SUPPORTED_FILTERS are shared between Encoders and Decoders
552 # since only lzip does not appear in both lists. lzip is a special
553 # case anyway, so it is handled separately in the Decoders section.
554 set(SUPPORTED_FILTERS
555     lzma1
556     lzma2
557     delta
558     "${SIMPLE_FILTERS}"
561 set(ENCODERS "${SUPPORTED_FILTERS}" CACHE STRING "Encoders to support")
563 # If LZMA2 is enabled, then LZMA1 must also be enabled.
564 if(NOT "lzma1" IN_LIST ENCODERS AND "lzma2" IN_LIST ENCODERS)
565     message(FATAL_ERROR "LZMA2 encoder requires that LZMA1 is also enabled")
566 endif()
568 # If LZMA1 is enabled, then at least one match finder must be enabled.
569 if(MATCH_FINDERS STREQUAL "" AND "lzma1" IN_LIST ENCODERS)
570     message(FATAL_ERROR "At least 1 match finder is required for an "
571                         "LZ-based encoder")
572 endif()
574 set(HAVE_DELTA_CODER OFF)
575 set(SIMPLE_ENCODERS OFF)
576 set(HAVE_ENCODERS OFF)
578 foreach(ENCODER IN LISTS ENCODERS)
579     if(ENCODER IN_LIST SUPPORTED_FILTERS)
580         set(HAVE_ENCODERS ON)
582         if(NOT SIMPLE_ENCODERS AND ENCODER IN_LIST SIMPLE_FILTERS)
583             set(SIMPLE_ENCODERS ON)
584         endif()
586         string(TOUPPER "${ENCODER}" ENCODER_UPPER)
587         add_compile_definitions("HAVE_ENCODER_${ENCODER_UPPER}")
588     else()
589         message(FATAL_ERROR "'${ENCODER}' is not a supported encoder")
590     endif()
591 endforeach()
593 if(HAVE_ENCODERS)
594     add_compile_definitions(HAVE_ENCODERS)
596     target_sources(liblzma PRIVATE
597         src/liblzma/common/alone_encoder.c
598         src/liblzma/common/block_buffer_encoder.c
599         src/liblzma/common/block_buffer_encoder.h
600         src/liblzma/common/block_encoder.c
601         src/liblzma/common/block_encoder.h
602         src/liblzma/common/block_header_encoder.c
603         src/liblzma/common/easy_buffer_encoder.c
604         src/liblzma/common/easy_encoder.c
605         src/liblzma/common/easy_encoder_memusage.c
606         src/liblzma/common/filter_buffer_encoder.c
607         src/liblzma/common/filter_encoder.c
608         src/liblzma/common/filter_encoder.h
609         src/liblzma/common/filter_flags_encoder.c
610         src/liblzma/common/index_encoder.c
611         src/liblzma/common/index_encoder.h
612         src/liblzma/common/stream_buffer_encoder.c
613         src/liblzma/common/stream_encoder.c
614         src/liblzma/common/stream_flags_encoder.c
615         src/liblzma/common/vli_encoder.c
616     )
618     if(ENABLE_THREADS)
619         target_sources(liblzma PRIVATE
620             src/liblzma/common/stream_encoder_mt.c
621         )
622     endif()
624     if(SIMPLE_ENCODERS)
625         target_sources(liblzma PRIVATE
626             src/liblzma/simple/simple_encoder.c
627             src/liblzma/simple/simple_encoder.h
628         )
629     endif()
631     if("lzma1" IN_LIST ENCODERS)
632         target_sources(liblzma PRIVATE
633             src/liblzma/lzma/lzma_encoder.c
634             src/liblzma/lzma/lzma_encoder.h
635             src/liblzma/lzma/lzma_encoder_optimum_fast.c
636             src/liblzma/lzma/lzma_encoder_optimum_normal.c
637             src/liblzma/lzma/lzma_encoder_private.h
638             src/liblzma/lzma/fastpos.h
639             src/liblzma/lz/lz_encoder.c
640             src/liblzma/lz/lz_encoder.h
641             src/liblzma/lz/lz_encoder_hash.h
642             src/liblzma/lz/lz_encoder_hash_table.h
643             src/liblzma/lz/lz_encoder_mf.c
644             src/liblzma/rangecoder/price.h
645             src/liblzma/rangecoder/price_table.c
646             src/liblzma/rangecoder/range_encoder.h
647         )
649         if(NOT ENABLE_SMALL)
650             target_sources(liblzma PRIVATE src/liblzma/lzma/fastpos_table.c)
651         endif()
652     endif()
654     if("lzma2" IN_LIST ENCODERS)
655         target_sources(liblzma PRIVATE
656             src/liblzma/lzma/lzma2_encoder.c
657             src/liblzma/lzma/lzma2_encoder.h
658         )
659     endif()
661     if("delta" IN_LIST ENCODERS)
662         set(HAVE_DELTA_CODER ON)
663         target_sources(liblzma PRIVATE
664             src/liblzma/delta/delta_encoder.c
665             src/liblzma/delta/delta_encoder.h
666         )
667     endif()
668 endif()
671 ############
672 # Decoders #
673 ############
675 set(DECODERS "${SUPPORTED_FILTERS}" CACHE STRING "Decoders to support")
677 set(SIMPLE_DECODERS OFF)
678 set(HAVE_DECODERS OFF)
680 foreach(DECODER IN LISTS DECODERS)
681     if(DECODER IN_LIST SUPPORTED_FILTERS)
682         set(HAVE_DECODERS ON)
684         if(NOT SIMPLE_DECODERS AND DECODER IN_LIST SIMPLE_FILTERS)
685             set(SIMPLE_DECODERS ON)
686         endif()
688         string(TOUPPER "${DECODER}" DECODER_UPPER)
689         add_compile_definitions("HAVE_DECODER_${DECODER_UPPER}")
690     else()
691         message(FATAL_ERROR "'${DECODER}' is not a supported decoder")
692     endif()
693 endforeach()
695 if(HAVE_DECODERS)
696     add_compile_definitions(HAVE_DECODERS)
698     target_sources(liblzma PRIVATE
699         src/liblzma/common/alone_decoder.c
700         src/liblzma/common/alone_decoder.h
701         src/liblzma/common/auto_decoder.c
702         src/liblzma/common/block_buffer_decoder.c
703         src/liblzma/common/block_decoder.c
704         src/liblzma/common/block_decoder.h
705         src/liblzma/common/block_header_decoder.c
706         src/liblzma/common/easy_decoder_memusage.c
707         src/liblzma/common/file_info.c
708         src/liblzma/common/filter_buffer_decoder.c
709         src/liblzma/common/filter_decoder.c
710         src/liblzma/common/filter_decoder.h
711         src/liblzma/common/filter_flags_decoder.c
712         src/liblzma/common/index_decoder.c
713         src/liblzma/common/index_decoder.h
714         src/liblzma/common/index_hash.c
715         src/liblzma/common/stream_buffer_decoder.c
716         src/liblzma/common/stream_decoder.c
717         src/liblzma/common/stream_flags_decoder.c
718         src/liblzma/common/stream_decoder.h
719         src/liblzma/common/vli_decoder.c
720     )
722     if(ENABLE_THREADS)
723         target_sources(liblzma PRIVATE
724             src/liblzma/common/stream_decoder_mt.c
725         )
726     endif()
728     if(SIMPLE_DECODERS)
729         target_sources(liblzma PRIVATE
730             src/liblzma/simple/simple_decoder.c
731             src/liblzma/simple/simple_decoder.h
732         )
733     endif()
735     if("lzma1" IN_LIST DECODERS)
736         target_sources(liblzma PRIVATE
737             src/liblzma/lzma/lzma_decoder.c
738             src/liblzma/lzma/lzma_decoder.h
739             src/liblzma/rangecoder/range_decoder.h
740             src/liblzma/lz/lz_decoder.c
741             src/liblzma/lz/lz_decoder.h
742         )
743     endif()
745     if("lzma2" IN_LIST DECODERS)
746         target_sources(liblzma PRIVATE
747             src/liblzma/lzma/lzma2_decoder.c
748             src/liblzma/lzma/lzma2_decoder.h
749         )
750     endif()
752     if("delta" IN_LIST DECODERS)
753         set(HAVE_DELTA_CODER ON)
754         target_sources(liblzma PRIVATE
755             src/liblzma/delta/delta_decoder.c
756             src/liblzma/delta/delta_decoder.h
757         )
758     endif()
759 endif()
761 # Some sources must appear if the filter is configured as either
762 # an encoder or decoder.
763 if("lzma1" IN_LIST ENCODERS OR "lzma1" IN_LIST DECODERS)
764     target_sources(liblzma PRIVATE
765         src/liblzma/rangecoder/range_common.h
766         src/liblzma/lzma/lzma_encoder_presets.c
767         src/liblzma/lzma/lzma_common.h
768     )
769 endif()
771 if(HAVE_DELTA_CODER)
772     target_sources(liblzma PRIVATE
773         src/liblzma/delta/delta_common.c
774         src/liblzma/delta/delta_common.h
775         src/liblzma/delta/delta_private.h
776     )
777 endif()
779 if(SIMPLE_ENCODERS OR SIMPLE_DECODERS)
780     target_sources(liblzma PRIVATE
781         src/liblzma/simple/simple_coder.c
782         src/liblzma/simple/simple_coder.h
783         src/liblzma/simple/simple_private.h
784     )
785 endif()
787 foreach(SIMPLE_CODER IN LISTS SIMPLE_FILTERS)
788     if(SIMPLE_CODER IN_LIST ENCODERS OR SIMPLE_CODER IN_LIST DECODERS)
789         target_sources(liblzma PRIVATE "src/liblzma/simple/${SIMPLE_CODER}.c")
790     endif()
791 endforeach()
794 #############
795 # MicroLZMA #
796 #############
798 option(MICROLZMA_ENCODER
799        "MicroLZMA encoder (needed by specific applications only)" ON)
801 option(MICROLZMA_DECODER
802        "MicroLZMA decoder (needed by specific applications only)" ON)
804 if(MICROLZMA_ENCODER)
805     if(NOT "lzma1" IN_LIST ENCODERS)
806         message(FATAL_ERROR "The LZMA1 encoder is required to support the "
807                             "MicroLZMA encoder")
808     endif()
810     target_sources(liblzma PRIVATE src/liblzma/common/microlzma_encoder.c)
811 endif()
813 if(MICROLZMA_DECODER)
814     if(NOT "lzma1" IN_LIST DECODERS)
815         message(FATAL_ERROR "The LZMA1 decoder is required to support the "
816                             "MicroLZMA decoder")
817     endif()
819     target_sources(liblzma PRIVATE src/liblzma/common/microlzma_decoder.c)
820 endif()
823 #############################
824 # lzip (.lz) format support #
825 #############################
827 option(LZIP_DECODER "Support lzip decoder" ON)
829 if(LZIP_DECODER)
830     # If lzip decoder support is requested, make sure LZMA1 decoder is enabled.
831     if(NOT "lzma1" IN_LIST DECODERS)
832         message(FATAL_ERROR "The LZMA1 decoder is required to support the "
833                             "lzip decoder")
834     endif()
836     add_compile_definitions(HAVE_LZIP_DECODER)
838     target_sources(liblzma PRIVATE
839         src/liblzma/common/lzip_decoder.c
840         src/liblzma/common/lzip_decoder.h
841     )
842 endif()
845 ##############
846 # Sandboxing #
847 ##############
849 # ON        Use sandboxing if a supported method is available in the OS.
850 # OFF       Disable sandboxing.
851 # capsicum  Require Capsicum (FreeBSD >= 10.2) and fail if not found.
852 # pledge    Require pledge(2) (OpenBSD >= 5.9) and fail if not found.
853 # landlock  Require Landlock (Linux >= 5.13) and fail if not found.
854 set(SUPPORTED_SANDBOX_METHODS ON OFF capsicum pledge landlock)
856 set(ENABLE_SANDBOX ON CACHE STRING
857     "Sandboxing method to use in 'xz', 'xzdec', and 'lzmadec'")
859 set_property(CACHE ENABLE_SANDBOX
860                 PROPERTY STRINGS "${SUPPORTED_SANDBOX_METHODS}")
862 if(NOT ENABLE_SANDBOX IN_LIST SUPPORTED_SANDBOX_METHODS)
863     message(FATAL_ERROR "'${ENABLE_SANDBOX}' is not a supported "
864                         "sandboxing method")
865 endif()
867 # When autodetecting, the search order is fixed and we must not find
868 # more than one method.
869 if(ENABLE_SANDBOX STREQUAL "OFF")
870     set(SANDBOX_FOUND ON)
871 else()
872     set(SANDBOX_FOUND OFF)
873 endif()
875 # Since xz and xzdec can both use sandboxing, the compile definition needed
876 # to use the sandbox must be added to both targets.
877 set(SANDBOX_COMPILE_DEFINITION OFF)
879 # Sandboxing: Capsicum
880 if(NOT SANDBOX_FOUND AND ENABLE_SANDBOX MATCHES "^ON$|^capsicum$")
881     check_symbol_exists(cap_rights_limit sys/capsicum.h
882                         HAVE_CAP_RIGHTS_LIMIT)
883     if(HAVE_CAP_RIGHTS_LIMIT)
884         set(SANDBOX_COMPILE_DEFINITION "HAVE_CAP_RIGHTS_LIMIT")
885         set(SANDBOX_FOUND ON)
886     endif()
887 endif()
889 # Sandboxing: pledge(2)
890 if(NOT SANDBOX_FOUND AND ENABLE_SANDBOX MATCHES "^ON$|^pledge$")
891     check_symbol_exists(pledge unistd.h HAVE_PLEDGE)
892     if(HAVE_PLEDGE)
893         set(SANDBOX_COMPILE_DEFINITION "HAVE_PLEDGE")
894         set(SANDBOX_FOUND ON)
895     endif()
896 endif()
898 # Sandboxing: Landlock
899 if(NOT SANDBOX_FOUND AND ENABLE_SANDBOX MATCHES "^ON$|^landlock$")
900     check_include_file(linux/landlock.h HAVE_LINUX_LANDLOCK_H)
902     if(HAVE_LINUX_LANDLOCK_H)
903         set(SANDBOX_COMPILE_DEFINITION "HAVE_LINUX_LANDLOCK_H")
904         set(SANDBOX_FOUND ON)
906         # Of our three sandbox methods, only Landlock is incompatible
907         # with -fsanitize. FreeBSD 13.2 with Capsicum was tested with
908         # -fsanitize=address,undefined and had no issues. OpenBSD (as
909         # of version 7.4) has minimal support for process instrumentation.
910         # OpenBSD does not distribute the additional libraries needed
911         # (libasan, libubsan, etc.) with GCC or Clang needed for runtime
912         # sanitization support and instead only support
913         # -fsanitize-minimal-runtime for minimal undefined behavior
914         # sanitization. This minimal support is compatible with our use
915         # of the Pledge sandbox. So only Landlock will result in a
916         # build that cannot compress or decompress a single file to
917         # standard out.
918         if(CMAKE_C_FLAGS MATCHES "-fsanitize=")
919             message(SEND_ERROR
920                     "CMAKE_C_FLAGS or the environment variable CFLAGS "
921                     "contains '-fsanitize=' which is incompatible "
922                     "with Landlock sandboxing. Use -DENABLE_SANDBOX=OFF "
923                     "as an argument to 'cmake' when using '-fsanitize'.")
924         endif()
925     endif()
926 endif()
928 if(NOT SANDBOX_FOUND AND NOT ENABLE_SANDBOX MATCHES "^ON$|^OFF$")
929     message(SEND_ERROR "ENABLE_SANDBOX=${ENABLE_SANDBOX} was used but "
930                         "support for the sandboxing method wasn't found.")
931 endif()
935 # Put the tuklib functions under the lzma_ namespace.
936 target_compile_definitions(liblzma PRIVATE TUKLIB_SYMBOL_PREFIX=lzma_)
937 tuklib_cpucores(liblzma)
938 tuklib_physmem(liblzma)
940 # While liblzma can be built without tuklib_cpucores or tuklib_physmem
941 # modules, the liblzma API functions lzma_cputhreads() and lzma_physmem()
942 # will then be useless (which isn't too bad but still unfortunate). Since
943 # I expect the CMake-based builds to be only used on systems that are
944 # supported by these tuklib modules, problems with these tuklib modules
945 # are considered a hard error for now. This hopefully helps to catch bugs
946 # in the CMake versions of the tuklib checks.
947 if(NOT TUKLIB_CPUCORES_FOUND OR NOT TUKLIB_PHYSMEM_FOUND)
948     # Use SEND_ERROR instead of FATAL_ERROR. If someone reports a bug,
949     # seeing the results of the remaining checks can be useful too.
950     message(SEND_ERROR
951             "tuklib_cpucores() or tuklib_physmem() failed. "
952             "Unless you really are building for a system where these "
953             "modules are not supported (unlikely), this is a bug in the "
954             "included cmake/tuklib_*.cmake files that should be fixed. "
955             "To build anyway, edit this CMakeLists.txt to ignore this error.")
956 endif()
958 # Check for __attribute__((__constructor__)) support.
959 # This needs -Werror because some compilers just warn
960 # about this being unsupported.
961 cmake_push_check_state()
962 set(CMAKE_REQUIRED_FLAGS "-Werror")
963 check_c_source_compiles("
964         __attribute__((__constructor__))
965         static void my_constructor_func(void) { return; }
966         int main(void) { return 0; }
967     "
968     HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
969 cmake_pop_check_state()
970 tuklib_add_definition_if(liblzma HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
972 # The Win95 threading lacks a thread-safe one-time initialization function.
973 # The one-time initialization is needed for crc32_small.c and crc64_small.c
974 # create the CRC tables. So if small mode is enabled, the threading mode is
975 # win95, and the compiler does not support attribute constructor, then we
976 # would end up with a multithreaded build that is thread-unsafe. As a
977 # result this configuration is not allowed.
978 if(USE_WIN95_THREADS AND ENABLE_SMALL AND NOT HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
979     message(SEND_ERROR "Threading method win95 and ENABLE_SMALL "
980                         "cannot be used at the same time with a compiler "
981                         "that doesn't support "
982                         "__attribute__((__constructor__))")
983 endif()
986 # Check for __attribute__((__ifunc__())) support.
987 # Supported values for USE_ATTR_IFUNC:
989 # auto (default) - Detect ifunc support with a compile test.
990 # ON             - Always enable ifunc.
991 # OFF            - Disable ifunc usage.
992 set(USE_ATTR_IFUNC "auto" CACHE STRING "Use __attribute__((__ifunc__())).")
994 set(SUPPORTED_USE_ATTR_IFUNC auto ON OFF)
996 if(NOT USE_ATTR_IFUNC IN_LIST SUPPORTED_USE_ATTR_IFUNC)
997     message(FATAL_ERROR "'${USE_ATTR_IFUNC}' is not a supported value for"
998                         "USE_ATTR_IFUNC")
999 endif()
1001 # When USE_ATTR_IFUNC is 'auto', allow the use of __attribute__((__ifunc__()))
1002 # if compiler support is detected and we are building for GNU/Linux (glibc)
1003 # or FreeBSD. uClibc and musl don't support ifunc in their dynamic linkers
1004 # but some compilers still accept the attribute when compiling for these
1005 # C libraries, which results in broken binaries. That's why we need to
1006 # check which libc is being used.
1007 if(USE_ATTR_IFUNC STREQUAL "auto")
1008     cmake_push_check_state()
1009     set(CMAKE_REQUIRED_FLAGS "-Werror")
1011     check_c_source_compiles("
1012             /*
1013              * Force a compilation error when not using glibc on Linux
1014              * or if we are not using FreeBSD. uClibc will define
1015              * __GLIBC__ but does not support ifunc, so we must have
1016              * an extra check to disable with uClibc.
1017              */
1018             #if defined(__linux__)
1019             #   include <features.h>
1020             #   if !defined(__GLIBC__) || defined(__UCLIBC__)
1021             compile error
1022             #   endif
1023             #elif !defined(__FreeBSD__)
1024             compile error
1025             #endif
1027             static void func(void) { return; }
1028             static void (*resolve_func(void)) (void) { return func; }
1029             void func_ifunc(void)
1030                     __attribute__((__ifunc__(\"resolve_func\")));
1031             int main(void) { return 0; }
1032             /*
1033              * 'clang -Wall' incorrectly warns that resolve_func is
1034              * unused (-Wunused-function). Correct assembly output is
1035              * still produced. This problem exists at least in Clang
1036              * versions 4 to 17. The following silences the bogus warning:
1037              */
1038             void make_clang_quiet(void);
1039             void make_clang_quiet(void) { resolve_func()(); }
1040         "
1041         SYSTEM_SUPPORTS_IFUNC)
1043         cmake_pop_check_state()
1044 endif()
1046 if(USE_ATTR_IFUNC STREQUAL "ON" OR SYSTEM_SUPPORTS_IFUNC)
1047     tuklib_add_definitions(liblzma HAVE_FUNC_ATTRIBUTE_IFUNC)
1049     if(CMAKE_C_FLAGS MATCHES "-fsanitize=")
1050         message(SEND_ERROR
1051                 "CMAKE_C_FLAGS or the environment variable CFLAGS "
1052                 "contains '-fsanitize=' which is incompatible "
1053                 "with ifunc. Use -DUSE_ATTR_IFUNC=OFF "
1054                 "as an argument to 'cmake' when using '-fsanitize'.")
1055     endif()
1056 endif()
1058 # cpuid.h
1059 check_include_file(cpuid.h HAVE_CPUID_H)
1060 tuklib_add_definition_if(liblzma HAVE_CPUID_H)
1062 # immintrin.h:
1063 check_include_file(immintrin.h HAVE_IMMINTRIN_H)
1064 if(HAVE_IMMINTRIN_H)
1065     target_compile_definitions(liblzma PRIVATE HAVE_IMMINTRIN_H)
1067     # SSE2 intrinsics:
1068     check_c_source_compiles("
1069             #include <immintrin.h>
1070             int main(void)
1071             {
1072                 __m128i x = { 0 };
1073                 _mm_movemask_epi8(x);
1074                 return 0;
1075             }
1076         "
1077         HAVE__MM_MOVEMASK_EPI8)
1078     tuklib_add_definition_if(liblzma HAVE__MM_MOVEMASK_EPI8)
1080     # CLMUL intrinsic:
1081     option(ALLOW_CLMUL_CRC "Allow carryless multiplication for CRC \
1082 calculation if supported by the system" ON)
1084     if(ALLOW_CLMUL_CRC)
1085         check_c_source_compiles("
1086                 #include <immintrin.h>
1087                 #if defined(__e2k__) && __iset__ < 6
1088                 #   error
1089                 #endif
1090                 #if (defined(__GNUC__) || defined(__clang__)) \
1091                         && !defined(__EDG__)
1092                 __attribute__((__target__(\"ssse3,sse4.1,pclmul\")))
1093                 #endif
1094                 __m128i my_clmul(__m128i a)
1095                 {
1096                     const __m128i b = _mm_set_epi64x(1, 2);
1097                     return _mm_clmulepi64_si128(a, b, 0);
1098                 }
1099                 int main(void) { return 0; }
1100             "
1101             HAVE_USABLE_CLMUL)
1102         tuklib_add_definition_if(liblzma HAVE_USABLE_CLMUL)
1103     endif()
1104 endif()
1106 # ARM64 C Language Extensions define CRC32 functions in arm_acle.h.
1107 # These are supported by at least GCC and Clang which both need
1108 # __attribute__((__target__("+crc"))), unless the needed compiler flags
1109 # are used to support the CRC instruction.
1110 option(ALLOW_ARM64_CRC32 "Allow ARM64 CRC32 instruction if supported by \
1111 the system" ON)
1113 if(ALLOW_ARM64_CRC32)
1114     check_c_source_compiles("
1115             #include <stdint.h>
1117             #ifndef _MSC_VER
1118             #include <arm_acle.h>
1119             #endif
1121             #if (defined(__GNUC__) || defined(__clang__)) && !defined(__EDG__)
1122             __attribute__((__target__(\"+crc\")))
1123             #endif
1124             uint32_t my_crc(uint32_t a, uint64_t b)
1125             {
1126                 return __crc32d(a, b);
1127             }
1128             int main(void) { return 0; }
1129         "
1130         HAVE_ARM64_CRC32)
1132     if(HAVE_ARM64_CRC32)
1133         target_compile_definitions(liblzma PRIVATE HAVE_ARM64_CRC32)
1135         # Check for ARM64 CRC32 instruction runtime detection.
1136         # getauxval() is supported on Linux.
1137         check_symbol_exists(getauxval sys/auxv.h HAVE_GETAUXVAL)
1138         tuklib_add_definition_if(liblzma HAVE_GETAUXVAL)
1140         # elf_aux_info() is supported on FreeBSD.
1141         check_symbol_exists(elf_aux_info sys/auxv.h HAVE_ELF_AUX_INFO)
1142         tuklib_add_definition_if(liblzma HAVE_ELF_AUX_INFO)
1144         # sysctlbyname("hw.optional.armv8_crc32", ...) is supported on Darwin
1145         # (macOS, iOS, etc.). Note that sysctlbyname() is supported on FreeBSD,
1146         # NetBSD, and possibly others too but the string is specific to
1147         # Apple OSes. The C code is responsible for checking
1148         # defined(__APPLE__) before using
1149         # sysctlbyname("hw.optional.armv8_crc32", ...).
1150         check_symbol_exists(sysctlbyname sys/sysctl.h HAVE_SYSCTLBYNAME)
1151         tuklib_add_definition_if(liblzma HAVE_SYSCTLBYNAME)
1152     endif()
1153 endif()
1156 # Symbol visibility support:
1158 # The C_VISIBILITY_PRESET property takes care of adding the compiler
1159 # option -fvisibility=hidden (or equivalent) if and only if it is supported.
1161 # HAVE_VISIBILITY should always be defined to 0 or 1. It tells liblzma
1162 # if __attribute__((__visibility__("default")))
1163 # and __attribute__((__visibility__("hidden"))) are supported.
1164 # Those are useful only when the compiler supports -fvisibility=hidden
1165 # or such option so HAVE_VISIBILITY should be 1 only when both option and
1166 # the attribute support are present. HAVE_VISIBILITY is ignored on Windows
1167 # and Cygwin by the liblzma C code; __declspec(dllexport) is used instead.
1169 # CMake's GenerateExportHeader module is too fancy since liblzma already
1170 # has the necessary macros. Instead, check CMake's internal variable
1171 # CMAKE_C_COMPILE_OPTIONS_VISIBILITY (it's the C-specific variant of
1172 # CMAKE_<LANG>_COMPILE_OPTIONS_VISIBILITY) which contains the compiler
1173 # command line option for visibility support. It's empty or unset when
1174 # visibility isn't supported. (It was added to CMake 2.8.12 in the commit
1175 # 0e9f4bc00c6b26f254e74063e4026ac33b786513 in 2013.) This way we don't
1176 # set HAVE_VISIBILITY to 1 when visibility isn't actually supported.
1177 if(BUILD_SHARED_LIBS AND CMAKE_C_COMPILE_OPTIONS_VISIBILITY)
1178     set_target_properties(liblzma PROPERTIES C_VISIBILITY_PRESET hidden)
1179     target_compile_definitions(liblzma PRIVATE HAVE_VISIBILITY=1)
1180 else()
1181     target_compile_definitions(liblzma PRIVATE HAVE_VISIBILITY=0)
1182 endif()
1184 if(WIN32)
1185     if(BUILD_SHARED_LIBS)
1186         # Add the Windows resource file for liblzma.dll.
1187         target_sources(liblzma PRIVATE src/liblzma/liblzma_w32res.rc)
1189         set_target_properties(liblzma PROPERTIES
1190             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1191         )
1193         # Export the public API symbols with __declspec(dllexport).
1194         target_compile_definitions(liblzma PRIVATE DLL_EXPORT)
1196         if(NOT MSVC)
1197             # Create a DEF file. The linker puts the ordinal numbers there
1198             # too so the output from the linker isn't our final file.
1199             target_link_options(liblzma PRIVATE
1200                                 "-Wl,--output-def,liblzma.def.in")
1202             # Remove the ordinal numbers from the DEF file so that
1203             # no one will create an import library that links by ordinal
1204             # instead of by name. We don't maintain a DEF file so the
1205             # ordinal numbers aren't stable.
1206             add_custom_command(TARGET liblzma POST_BUILD
1207                 COMMAND "${CMAKE_COMMAND}"
1208                     -DINPUT_FILE=liblzma.def.in
1209                     -DOUTPUT_FILE=liblzma.def
1210                     -P
1211                     "${CMAKE_CURRENT_SOURCE_DIR}/cmake/remove-ordinals.cmake"
1212                 BYPRODUCTS "liblzma.def"
1213                 VERBATIM)
1214         endif()
1215     else()
1216         # Disable __declspec(dllimport) when linking against static liblzma.
1217         target_compile_definitions(liblzma INTERFACE LZMA_API_STATIC)
1218     endif()
1219 elseif(BUILD_SHARED_LIBS AND CMAKE_SYSTEM_NAME STREQUAL "Linux" AND
1220        NOT CMAKE_SYSTEM_PROCESSOR MATCHES "[Mm]icro[Bb]laze")
1221     # GNU/Linux-specific symbol versioning for shared liblzma.
1222     # This includes a few extra compatibility symbols for RHEL/CentOS 7
1223     # which are pointless on non-glibc non-Linux systems.
1224     #
1225     # As a special case, GNU/Linux on MicroBlaze gets the generic
1226     # symbol versioning because GCC 12 doesn't support the __symver__
1227     # attribute on MicroBlaze. On Linux, CMAKE_SYSTEM_PROCESSOR comes
1228     # from "uname -m" for native builds (should be "microblaze") or from
1229     # the CMake toolchain file (not perfectly standardized but it very
1230     # likely has "microblaze" in lower case or mixed case somewhere in
1231     # the string).
1232     #
1233     # FIXME? Avoid symvers on Linux with non-glibc like musl?
1234     #
1235     # Note that adding link options doesn't affect static builds
1236     # but HAVE_SYMBOL_VERSIONS_LINUX must not be used with static builds
1237     # because it would put symbol versions into the static library which
1238     # can cause problems. It's clearer if all symver related things are
1239     # omitted when not building a shared library.
1240     #
1241     # NOTE: Set it explicitly to 1 to make it clear that versioning is
1242     # done unconditionally in the C files.
1243     target_compile_definitions(liblzma PRIVATE HAVE_SYMBOL_VERSIONS_LINUX=1)
1244     target_link_options(liblzma PRIVATE
1245         "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_linux.map"
1246     )
1247     set_target_properties(liblzma PROPERTIES
1248         LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_linux.map"
1249     )
1250 elseif(BUILD_SHARED_LIBS AND (CMAKE_SYSTEM_NAME STREQUAL "FreeBSD" OR
1251                               CMAKE_SYSTEM_NAME STREQUAL "Linux"))
1252     # Generic symbol versioning for shared liblzma is used on FreeBSD and
1253     # also on GNU/Linux on MicroBlaze.
1254     target_link_options(liblzma PRIVATE
1255         "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_generic.map"
1256     )
1257     set_target_properties(liblzma PROPERTIES
1258         LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_generic.map"
1259     )
1260 endif()
1262 set_target_properties(liblzma PROPERTIES
1263     # At least for now the package versioning matches the rules used for
1264     # shared library versioning (excluding development releases) so it is
1265     # fine to use the package version here.
1266     SOVERSION "${xz_VERSION_MAJOR}"
1267     VERSION "${xz_VERSION}"
1269     # It's liblzma.so or liblzma.dll, not libliblzma.so or lzma.dll.
1270     # Avoid the name lzma.dll because it would conflict with LZMA SDK.
1271     PREFIX ""
1272     IMPORT_PREFIX ""
1275 # Create liblzma-config-version.cmake.
1277 # FIXME: SameMajorVersion is correct for stable releases but it is wrong
1278 # for development releases where each release may have incompatible changes.
1279 include(CMakePackageConfigHelpers)
1280 write_basic_package_version_file(
1281     "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config-version.cmake"
1282     VERSION "${liblzma_VERSION}"
1283     COMPATIBILITY SameMajorVersion)
1285 # Create liblzma-config.cmake. We use this spelling instead of
1286 # liblzmaConfig.cmake to make find_package work in case insensitive
1287 # manner even with case sensitive file systems. This gives more consistent
1288 # behavior between operating systems. This optionally includes a dependency
1289 # on a threading library, so the contents are created in two separate parts.
1290 # The "second half" is always needed, so create it first.
1291 set(LZMA_CONFIG_CONTENTS
1292 "include(\"\${CMAKE_CURRENT_LIST_DIR}/liblzma-targets.cmake\")
1294 if(NOT TARGET LibLZMA::LibLZMA)
1295     # Be compatible with the spelling used by the FindLibLZMA module. This
1296     # doesn't use ALIAS because it would make CMake resolve LibLZMA::LibLZMA
1297     # to liblzma::liblzma instead of keeping the original spelling. Keeping
1298     # the original spelling is important for good FindLibLZMA compatibility.
1299     add_library(LibLZMA::LibLZMA INTERFACE IMPORTED)
1300     set_target_properties(LibLZMA::LibLZMA PROPERTIES
1301                           INTERFACE_LINK_LIBRARIES liblzma::liblzma)
1302 endif()
1305 if(USE_POSIX_THREADS)
1306     set(LZMA_CONFIG_CONTENTS
1307 "include(CMakeFindDependencyMacro)
1308 set(THREADS_PREFER_PTHREAD_FLAG TRUE)
1309 find_dependency(Threads)
1311 ${LZMA_CONFIG_CONTENTS}
1313 endif()
1315 file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config.cmake"
1316         "${LZMA_CONFIG_CONTENTS}")
1318 # Create liblzma.pc.
1319 set(prefix "${CMAKE_INSTALL_PREFIX}")
1320 set(exec_prefix "${CMAKE_INSTALL_PREFIX}")
1321 set(libdir "${CMAKE_INSTALL_FULL_LIBDIR}")
1322 set(includedir "${CMAKE_INSTALL_FULL_INCLUDEDIR}")
1323 set(PTHREAD_CFLAGS "${CMAKE_THREAD_LIBS_INIT}")
1324 configure_file(src/liblzma/liblzma.pc.in liblzma.pc
1325                @ONLY
1326                NEWLINE_STYLE LF)
1328 # Install the library binary. The INCLUDES specifies the include path that
1329 # is exported for other projects to use but it doesn't install any files.
1330 install(TARGETS liblzma EXPORT liblzmaTargets
1331         RUNTIME  DESTINATION "${CMAKE_INSTALL_BINDIR}"
1332                  COMPONENT liblzma_Runtime
1333         LIBRARY  DESTINATION "${CMAKE_INSTALL_LIBDIR}"
1334                  COMPONENT liblzma_Runtime
1335                  NAMELINK_COMPONENT liblzma_Development
1336         ARCHIVE  DESTINATION "${CMAKE_INSTALL_LIBDIR}"
1337                  COMPONENT liblzma_Development
1338         INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
1340 # Install the liblzma API headers. These use a subdirectory so
1341 # this has to be done as a separate step.
1342 install(DIRECTORY src/liblzma/api/
1343         COMPONENT liblzma_Development
1344         DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
1345         FILES_MATCHING PATTERN "*.h")
1347 # Install the CMake files that other packages can use to find liblzma.
1348 set(liblzma_INSTALL_CMAKEDIR
1349     "${CMAKE_INSTALL_LIBDIR}/cmake/liblzma"
1350     CACHE STRING "Path to liblzma's .cmake files")
1352 install(EXPORT liblzmaTargets
1353         NAMESPACE liblzma::
1354         FILE liblzma-targets.cmake
1355         DESTINATION "${liblzma_INSTALL_CMAKEDIR}"
1356         COMPONENT liblzma_Development)
1358 install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config.cmake"
1359               "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config-version.cmake"
1360         DESTINATION "${liblzma_INSTALL_CMAKEDIR}"
1361         COMPONENT liblzma_Development)
1363 if(NOT MSVC)
1364     install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblzma.pc"
1365             DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig"
1366             COMPONENT liblzma_Development)
1367 endif()
1370 #############################################################################
1371 # Helper functions for installing files
1372 #############################################################################
1374 # For each non-empty element in the list LINK_NAMES, creates symbolic links
1375 # ${LINK_NAME}${LINK_SUFFIX} -> ${TARGET_NAME} in the directory ${DIR}.
1376 # The target file should exist because on Cygwin and MSYS2 symlink creation
1377 # can fail under certain conditions if the target doesn't exist.
1378 function(my_install_symlinks COMPONENT DIR TARGET_NAME LINK_SUFFIX LINK_NAMES)
1379     install(CODE "set(D \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/${DIR}\")
1380                  foreach(L ${LINK_NAMES})
1381                      file(CREATE_LINK \"${TARGET_NAME}\"
1382                                       \"\${D}/\${L}${LINK_SUFFIX}\"
1383                                       SYMBOLIC)
1384                  endforeach()"
1385             COMPONENT "${COMPONENT}")
1386 endfunction()
1388 # Installs a man page file of a given language ("" for the untranslated file)
1389 # and optionally its alternative names as symlinks. This is a helper function
1390 # for my_install_man() below.
1391 function(my_install_man_lang COMPONENT SRC_FILE MAN_LANG LINK_NAMES)
1392     # Get the man page section from the filename suffix.
1393     string(REGEX REPLACE "^.*\.([^/.]+)$" "\\1" MAN_SECTION "${SRC_FILE}")
1395     # A few man pages might be missing from translations.
1396     # Don't attempt to install them or create the related symlinks.
1397     if(NOT MAN_LANG STREQUAL "" AND NOT EXISTS "${SRC_FILE}")
1398         return()
1399     endif()
1401     # Installing the file must be done before creating the symlinks
1402     # due to Cygwin and MSYS2.
1403     install(FILES "${SRC_FILE}"
1404             DESTINATION "${CMAKE_INSTALL_MANDIR}/${MAN_LANG}/man${MAN_SECTION}"
1405             COMPONENT "${COMPONENT}")
1407     # Get the basename of the file to be used as the symlink target.
1408     get_filename_component(BASENAME "${SRC_FILE}" NAME)
1410     # LINK_NAMES don't contain the man page filename suffix (like ".1")
1411     # so it needs to be told to my_install_symlinks.
1412     my_install_symlinks("${COMPONENT}"
1413                         "${CMAKE_INSTALL_MANDIR}/${MAN_LANG}/man${MAN_SECTION}"
1414                         "${BASENAME}" ".${MAN_SECTION}" "${LINK_NAMES}")
1415 endfunction()
1417 # Installs a man page file and optionally its alternative names as symlinks.
1418 # Does the same for translations if ENABLE_NLS.
1419 function(my_install_man COMPONENT SRC_FILE LINK_NAMES)
1420     my_install_man_lang("${COMPONENT}" "${SRC_FILE}" "" "${LINK_NAMES}")
1422     if(ENABLE_NLS)
1423         # Find the translated versions of this man page.
1424         get_filename_component(BASENAME "${SRC_FILE}" NAME)
1425         file(GLOB MAN_FILES "po4a/man/*/${BASENAME}")
1427         foreach(F ${MAN_FILES})
1428             get_filename_component(MAN_LANG "${F}" DIRECTORY)
1429             get_filename_component(MAN_LANG "${MAN_LANG}" NAME)
1430             my_install_man_lang("${COMPONENT}" "${F}" "${MAN_LANG}"
1431                                 "${LINK_NAMES}")
1432         endforeach()
1433     endif()
1434 endfunction()
1437 #############################################################################
1438 # libgnu (getopt_long)
1439 #############################################################################
1441 # This mirrors how the Autotools build system handles the getopt_long
1442 # replacement, calling the object library libgnu since the replacement
1443 # version comes from Gnulib.
1444 add_library(libgnu OBJECT)
1446 # CMake requires that even an object library must have at least once source
1447 # file. So we give it a header file that results in no output files.
1449 # NOTE: Using a file outside the lib directory makes it possible to
1450 # delete lib/*.h and lib/*.c and still keep the build working if
1451 # getopt_long replacement isn't needed. It's convenient if one wishes
1452 # to be certain that no GNU LGPL code gets included in the binaries.
1453 target_sources(libgnu PRIVATE src/common/sysdefs.h)
1455 # The Ninja Generator requires setting the linker language since it cannot
1456 # guess the programming language of just a header file. Setting this
1457 # property avoids needing an empty .c file or an non-empty unnecessary .c
1458 # file.
1459 set_target_properties(libgnu PROPERTIES LINKER_LANGUAGE C)
1461 # Create /lib directory in the build directory and add it to the include path.
1462 file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/lib")
1463 target_include_directories(libgnu PUBLIC "${CMAKE_CURRENT_BINARY_DIR}/lib")
1465 # Include /lib from the source directory. It does no harm even if none of
1466 # the Gnulib replacements are used.
1467 target_include_directories(libgnu PUBLIC lib)
1469 # The command line tools need getopt_long in order to parse arguments. If
1470 # the system does not have a getopt_long implementation we can use the one
1471 # from Gnulib instead.
1472 check_symbol_exists(getopt_long getopt.h HAVE_GETOPT_LONG)
1474 if(NOT HAVE_GETOPT_LONG)
1475     # Set the __GETOPT_PREFIX definition to "rpl_" (replacement) to avoid
1476     # name conflicts with libc symbols. The same prefix is set if using
1477     # the Autotools build (m4/getopt.m4).
1478     target_compile_definitions(libgnu PUBLIC "__GETOPT_PREFIX=rpl_")
1480     # Create a custom copy command to copy the getopt header to the build
1481     # directory and re-copy it if it is updated. (Gnulib does it this way
1482     # because it allows choosing which .in.h files to actually use in the
1483     # build. We need just getopt.h so this is a bit overcomplicated for
1484     # a single header file only.)
1485     add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1486         COMMAND "${CMAKE_COMMAND}" -E copy
1487             "${CMAKE_CURRENT_SOURCE_DIR}/lib/getopt.in.h"
1488             "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1489         MAIN_DEPENDENCY "${CMAKE_CURRENT_SOURCE_DIR}/lib/getopt.in.h"
1490         VERBATIM)
1492     target_sources(libgnu PRIVATE
1493         lib/getopt1.c
1494         lib/getopt.c
1495         lib/getopt_int.h
1496         lib/getopt-cdefs.h
1497         lib/getopt-core.h
1498         lib/getopt-ext.h
1499         lib/getopt-pfx-core.h
1500         lib/getopt-pfx-ext.h
1501         "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1502     )
1503 endif()
1506 #############################################################################
1507 # xzdec and lzmadec
1508 #############################################################################
1510 if(HAVE_DECODERS AND (NOT MSVC OR MSVC_VERSION GREATER_EQUAL 1900))
1511     foreach(XZDEC xzdec lzmadec)
1512         add_executable("${XZDEC}"
1513             src/common/sysdefs.h
1514             src/common/tuklib_common.h
1515             src/common/tuklib_config.h
1516             src/common/tuklib_exit.c
1517             src/common/tuklib_exit.h
1518             src/common/tuklib_gettext.h
1519             src/common/tuklib_progname.c
1520             src/common/tuklib_progname.h
1521             src/xzdec/xzdec.c
1522         )
1524         target_include_directories("${XZDEC}" PRIVATE
1525             src/common
1526             src/liblzma/api
1527         )
1529         target_link_libraries("${XZDEC}" PRIVATE liblzma libgnu)
1531         if(WIN32)
1532             # Add the Windows resource file for xzdec.exe or lzmadec.exe.
1533             target_sources("${XZDEC}" PRIVATE src/xzdec/xzdec_w32res.rc)
1534             set_target_properties("${XZDEC}" PROPERTIES
1535                 LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1536             )
1537         endif()
1539         if(SANDBOX_COMPILE_DEFINITION)
1540             target_compile_definitions("${XZDEC}" PRIVATE
1541                                     "${SANDBOX_COMPILE_DEFINITION}")
1542         endif()
1544         tuklib_progname("${XZDEC}")
1546         install(TARGETS "${XZDEC}"
1547                 RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1548                         COMPONENT "${XZDEC}_Runtime")
1549     endforeach()
1551     # This is the only build-time difference with lzmadec.
1552     target_compile_definitions(lzmadec PRIVATE "LZMADEC")
1554     if(UNIX)
1555         # NOTE: This puts the lzmadec.1 symlinks into xzdec_Documentation.
1556         # This isn't great but doing them separately with translated
1557         # man pages would require extra code. So this has to suffice for now.
1558         my_install_man(xzdec_Documentation src/xzdec/xzdec.1 lzmadec)
1559     endif()
1560 endif()
1563 #############################################################################
1564 # lzmainfo
1565 #############################################################################
1567 if(HAVE_DECODERS AND (NOT MSVC OR MSVC_VERSION GREATER_EQUAL 1900))
1568     add_executable(lzmainfo
1569         src/common/sysdefs.h
1570         src/common/tuklib_common.h
1571         src/common/tuklib_config.h
1572         src/common/tuklib_exit.c
1573         src/common/tuklib_exit.h
1574         src/common/tuklib_gettext.h
1575         src/common/tuklib_progname.c
1576         src/common/tuklib_progname.h
1577         src/lzmainfo/lzmainfo.c
1578     )
1580     target_include_directories(lzmainfo PRIVATE
1581         src/common
1582         src/liblzma/api
1583     )
1585     target_link_libraries(lzmainfo PRIVATE liblzma libgnu)
1587     if(WIN32)
1588         # Add the Windows resource file for lzmainfo.exe.
1589         target_sources(lzmainfo PRIVATE src/lzmainfo/lzmainfo_w32res.rc)
1590         set_target_properties(lzmainfo PROPERTIES
1591             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1592         )
1593     endif()
1595     tuklib_progname(lzmainfo)
1597     # NOTE: The translations are in the "xz" domain and the .mo files are
1598     # installed as part of the "xz" target.
1599     if(ENABLE_NLS)
1600         target_link_libraries(lzmainfo PRIVATE Intl::Intl)
1602         target_compile_definitions(lzmainfo PRIVATE
1603                 ENABLE_NLS
1604                 PACKAGE="${TRANSLATION_DOMAIN}"
1605                 LOCALEDIR="${LOCALEDIR_DEFINITION}"
1606         )
1607     endif()
1609     install(TARGETS lzmainfo
1610             RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1611                     COMPONENT lzmainfo_Runtime)
1613     if(UNIX)
1614         my_install_man(lzmainfo_Documentation src/lzmainfo/lzmainfo.1 "")
1615     endif()
1616 endif()
1619 #############################################################################
1620 # xz
1621 #############################################################################
1623 if(NOT MSVC OR MSVC_VERSION GREATER_EQUAL 1900)
1624     add_executable(xz
1625         src/common/mythread.h
1626         src/common/sysdefs.h
1627         src/common/tuklib_common.h
1628         src/common/tuklib_config.h
1629         src/common/tuklib_exit.c
1630         src/common/tuklib_exit.h
1631         src/common/tuklib_gettext.h
1632         src/common/tuklib_integer.h
1633         src/common/tuklib_mbstr.h
1634         src/common/tuklib_mbstr_fw.c
1635         src/common/tuklib_mbstr_width.c
1636         src/common/tuklib_open_stdxxx.c
1637         src/common/tuklib_open_stdxxx.h
1638         src/common/tuklib_progname.c
1639         src/common/tuklib_progname.h
1640         src/xz/args.c
1641         src/xz/args.h
1642         src/xz/coder.c
1643         src/xz/coder.h
1644         src/xz/file_io.c
1645         src/xz/file_io.h
1646         src/xz/hardware.c
1647         src/xz/hardware.h
1648         src/xz/main.c
1649         src/xz/main.h
1650         src/xz/message.c
1651         src/xz/message.h
1652         src/xz/mytime.c
1653         src/xz/mytime.h
1654         src/xz/options.c
1655         src/xz/options.h
1656         src/xz/private.h
1657         src/xz/sandbox.c
1658         src/xz/sandbox.h
1659         src/xz/signals.c
1660         src/xz/signals.h
1661         src/xz/suffix.c
1662         src/xz/suffix.h
1663         src/xz/util.c
1664         src/xz/util.h
1665     )
1667     target_include_directories(xz PRIVATE
1668         src/common
1669         src/liblzma/api
1670     )
1672     if(HAVE_DECODERS)
1673         target_sources(xz PRIVATE
1674             src/xz/list.c
1675             src/xz/list.h
1676         )
1677     endif()
1679     target_link_libraries(xz PRIVATE liblzma libgnu)
1681     target_compile_definitions(xz PRIVATE ASSUME_RAM=128)
1683     if(WIN32)
1684         # Add the Windows resource file for xz.exe.
1685         target_sources(xz PRIVATE src/xz/xz_w32res.rc)
1686         set_target_properties(xz PROPERTIES
1687             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1688         )
1689     endif()
1691     if(SANDBOX_COMPILE_DEFINITION)
1692         target_compile_definitions(xz PRIVATE "${SANDBOX_COMPILE_DEFINITION}")
1693     endif()
1695     tuklib_progname(xz)
1696     tuklib_mbstr(xz)
1698     check_symbol_exists(optreset getopt.h HAVE_OPTRESET)
1699     tuklib_add_definition_if(xz HAVE_OPTRESET)
1701     check_symbol_exists(posix_fadvise fcntl.h HAVE_POSIX_FADVISE)
1702     tuklib_add_definition_if(xz HAVE_POSIX_FADVISE)
1704     # How to get file time:
1705     check_struct_has_member("struct stat" st_atim.tv_nsec
1706                             "sys/types.h;sys/stat.h"
1707                             HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1708     if(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1709         tuklib_add_definitions(xz HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1710     else()
1711         check_struct_has_member("struct stat" st_atimespec.tv_nsec
1712                                 "sys/types.h;sys/stat.h"
1713                                 HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1714         if(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1715             tuklib_add_definitions(xz HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1716         else()
1717             check_struct_has_member("struct stat" st_atimensec
1718                                     "sys/types.h;sys/stat.h"
1719                                     HAVE_STRUCT_STAT_ST_ATIMENSEC)
1720             tuklib_add_definition_if(xz HAVE_STRUCT_STAT_ST_ATIMENSEC)
1721         endif()
1722     endif()
1724     # How to set file time:
1725     check_symbol_exists(futimens "sys/types.h;sys/stat.h" HAVE_FUTIMENS)
1726     if(HAVE_FUTIMENS)
1727         tuklib_add_definitions(xz HAVE_FUTIMENS)
1728     else()
1729         check_symbol_exists(futimes "sys/time.h" HAVE_FUTIMES)
1730         if(HAVE_FUTIMES)
1731             tuklib_add_definitions(xz HAVE_FUTIMES)
1732         else()
1733             check_symbol_exists(futimesat "sys/time.h" HAVE_FUTIMESAT)
1734             if(HAVE_FUTIMESAT)
1735                 tuklib_add_definitions(xz HAVE_FUTIMESAT)
1736             else()
1737                 check_symbol_exists(utimes "sys/time.h" HAVE_UTIMES)
1738                 if(HAVE_UTIMES)
1739                     tuklib_add_definitions(xz HAVE_UTIMES)
1740                 else()
1741                     check_symbol_exists(_futime "sys/utime.h" HAVE__FUTIME)
1742                     if(HAVE__FUTIME)
1743                         tuklib_add_definitions(xz HAVE__FUTIME)
1744                     else()
1745                         check_symbol_exists(utime "utime.h" HAVE_UTIME)
1746                         tuklib_add_definition_if(xz HAVE_UTIME)
1747                     endif()
1748                 endif()
1749             endif()
1750         endif()
1751     endif()
1753     if(ENABLE_NLS)
1754         target_link_libraries(xz PRIVATE Intl::Intl)
1756         target_compile_definitions(xz PRIVATE
1757                 ENABLE_NLS
1758                 PACKAGE="${TRANSLATION_DOMAIN}"
1759                 LOCALEDIR="${LOCALEDIR_DEFINITION}"
1760         )
1762         file(STRINGS po/LINGUAS LINGUAS)
1764         # Where to find .gmo files. If msgfmt is available, the .po files
1765         # will be converted as part of the build. Otherwise we will use
1766         # the pre-generated .gmo files which are included in XZ Utils
1767         # tarballs by Autotools.
1768         set(GMO_DIR "${CMAKE_CURRENT_SOURCE_DIR}/po")
1770         if(GETTEXT_FOUND)
1771             # NOTE: gettext_process_po_files' INSTALL_DESTINATION is
1772             # incompatible with how Autotools requires the .po files to
1773             # be named. CMake would require each .po file to be named with
1774             # the translation domain and thus each .po file would need its
1775             # own language-specific directory (like "po/fi/xz.po"). On top
1776             # of this, INSTALL_DESTINATION doesn't allow specifying COMPONENT
1777             # and thus the .mo files go into "Unspecified" component. So we
1778             # can use gettext_process_po_files to convert the .po files but
1779             # installation needs to be done with our own code.
1780             #
1781             # Also, the .gmo files will go to root of the build directory
1782             # instead of neatly into a subdirectory. This is hardcoded in
1783             # CMake's FindGettext.cmake.
1784             foreach(LANG IN LISTS LINGUAS)
1785                 gettext_process_po_files("${LANG}" ALL
1786                         PO_FILES "${CMAKE_CURRENT_SOURCE_DIR}/po/${LANG}.po")
1787             endforeach()
1789             set(GMO_DIR "${CMAKE_CURRENT_BINARY_DIR}")
1790         endif()
1792         foreach(LANG IN LISTS LINGUAS)
1793             install(
1794                 FILES "${GMO_DIR}/${LANG}.gmo"
1795                 DESTINATION "${CMAKE_INSTALL_LOCALEDIR}/${LANG}/LC_MESSAGES"
1796                 RENAME "${TRANSLATION_DOMAIN}.mo"
1797                 COMPONENT xz_Runtime)
1798         endforeach()
1799     endif()
1801     # This command must be before the symlink creation to keep things working
1802     # on Cygwin and MSYS2 in all cases.
1803     #
1804     #   - Cygwin can encode symlinks in multiple ways. This can be
1805     #     controlled via the environment variable "CYGWIN". If it contains
1806     #     "winsymlinks:nativestrict" then symlink creation will fail if
1807     #     the link target doesn't exist. This mode isn't the default though.
1808     #     See: https://cygwin.com/faq.html#faq.api.symlinks
1809     #
1810     #   - MSYS2 supports the same winsymlinks option in the environment
1811     #     variable "MSYS" (not "MSYS2). The default in MSYS2 is to make
1812     #     a copy of the file instead of any kind of symlink. Thus the link
1813     #     target must exist or the creation of the "symlink" (copy) will fail.
1814     #
1815     # Our installation order must be such that when a symbolic link is created
1816     # its target must already exists. There is no race condition for parallel
1817     # builds because the generated cmake_install.cmake executes serially.
1818     install(TARGETS xz
1819             RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1820                     COMPONENT xz_Runtime)
1822     if(UNIX)
1823         option(CREATE_XZ_SYMLINKS "Create unxz and xzcat symlinks" ON)
1824         option(CREATE_LZMA_SYMLINKS "Create lzma, unlzma, and lzcat symlinks"
1825                ON)
1826         set(XZ_LINKS)
1828         if(CREATE_XZ_SYMLINKS)
1829             list(APPEND XZ_LINKS "unxz" "xzcat")
1830         endif()
1832         if(CREATE_LZMA_SYMLINKS)
1833             list(APPEND XZ_LINKS "lzma" "unlzma" "lzcat")
1834         endif()
1836         # On Cygwin, don't add the .exe suffix to the symlinks.
1837         #
1838         # FIXME? Does this make sense on MSYS & MSYS2 where "ln -s"
1839         # by default makes copies? Inside MSYS & MSYS2 it is possible
1840         # to execute files without the .exe suffix but not outside
1841         # (like in Command Prompt). Omitting the suffix matches
1842         # what configure.ac has done for many years though.
1843         my_install_symlinks(xz_Runtime "${CMAKE_INSTALL_BINDIR}"
1844                             "xz${CMAKE_EXECUTABLE_SUFFIX}" "" "${XZ_LINKS}")
1846         # Install the man pages and (optionally) their symlinks
1847         # and translations.
1848         my_install_man(xz_Documentation src/xz/xz.1 "${XZ_LINKS}")
1849     endif()
1850 endif()
1853 #############################################################################
1854 # Scripts
1855 #############################################################################
1857 if(UNIX)
1858     # NOTE: This isn't as sophisticated as in the Autotools build which
1859     # uses posix-shell.m4 but hopefully this doesn't need to be either.
1860     # CMake likely won't be used on as many (old) obscure systems as the
1861     # Autotools-based builds are.
1862     if(CMAKE_SYSTEM_NAME STREQUAL "SunOS" AND EXISTS "/usr/xpg4/bin/sh")
1863         set(POSIX_SHELL_DEFAULT "/usr/xpg4/bin/sh")
1864     else()
1865         set(POSIX_SHELL_DEFAULT "/bin/sh")
1866     endif()
1868     set(POSIX_SHELL "${POSIX_SHELL_DEFAULT}" CACHE STRING
1869         "Shell to use for scripts (xzgrep and others)")
1871     # Guess the extra path to add from POSIX_SHELL. Autotools-based build
1872     # has a separate option --enable-path-for-scripts=PREFIX but this is
1873     # enough for Solaris.
1874     set(enable_path_for_scripts)
1875     get_filename_component(POSIX_SHELL_DIR "${POSIX_SHELL}" DIRECTORY)
1877     if(NOT POSIX_SHELL_DIR STREQUAL "/bin" AND
1878             NOT POSIX_SHELL_DIR STREQUAL "/usr/bin")
1879         set(enable_path_for_scripts "PATH=${POSIX_SHELL_DIR}:\$PATH")
1880     endif()
1882     set(XZDIFF_LINKS xzcmp)
1883     set(XZGREP_LINKS xzegrep xzfgrep)
1884     set(XZMORE_LINKS)
1885     set(XZLESS_LINKS)
1887     if(CREATE_LZMA_SYMLINKS)
1888         list(APPEND XZDIFF_LINKS lzdiff lzcmp)
1889         list(APPEND XZGREP_LINKS lzgrep lzegrep lzfgrep)
1890         list(APPEND XZMORE_LINKS lzmore)
1891         list(APPEND XZLESS_LINKS lzless)
1892     endif()
1894     set(xz "xz")
1896     foreach(S xzdiff xzgrep xzmore xzless)
1897         configure_file("src/scripts/${S}.in" "${S}"
1898                @ONLY
1899                NEWLINE_STYLE LF)
1901         install(PROGRAMS "${CMAKE_CURRENT_BINARY_DIR}/${S}"
1902                 DESTINATION "${CMAKE_INSTALL_BINDIR}"
1903                 COMPONENT scripts_Runtime)
1904     endforeach()
1906     # file(CHMOD ...) would need CMake 3.19 so use execute_process instead.
1907     # Using +x is fine even if umask was 077. If execute bit is set at all
1908     # then "make install" will set it for group and other access bits too.
1909     execute_process(COMMAND chmod +x xzdiff xzgrep xzmore xzless
1910                     WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}")
1912     unset(xz)
1913     unset(POSIX_SHELL)
1914     unset(enable_path_for_scripts)
1916     my_install_symlinks(scripts_Runtime "${CMAKE_INSTALL_BINDIR}" xzdiff ""
1917                         "${XZDIFF_LINKS}")
1919     my_install_symlinks(scripts_Runtime "${CMAKE_INSTALL_BINDIR}" xzgrep ""
1920                         "${XZGREP_LINKS}")
1922     my_install_symlinks(scripts_Runtime "${CMAKE_INSTALL_BINDIR}" xzmore ""
1923                         "${XZMORE_LINKS}")
1925     my_install_symlinks(scripts_Runtime "${CMAKE_INSTALL_BINDIR}" xzless ""
1926                         "${XZLESS_LINKS}")
1928     my_install_man(scripts_Documentation src/scripts/xzdiff.1 "${XZDIFF_LINKS}")
1929     my_install_man(scripts_Documentation src/scripts/xzgrep.1 "${XZGREP_LINKS}")
1930     my_install_man(scripts_Documentation src/scripts/xzmore.1 "${XZMORE_LINKS}")
1931     my_install_man(scripts_Documentation src/scripts/xzless.1 "${XZLESS_LINKS}")
1932 endif()
1935 #############################################################################
1936 # Documentation
1937 #############################################################################
1939 # Use OPTIONAL because doc/api might not exist. The liblzma API docs
1940 # can be generated by running "doxygen/update-doxygen".
1941 install(DIRECTORY doc/api doc/examples
1942         DESTINATION "${CMAKE_INSTALL_DOCDIR}"
1943         COMPONENT liblzma_Documentation
1944         OPTIONAL)
1946 # GPLv2 applies to the scripts. If GNU getopt_long is used then
1947 # LGPLv2.1 applies to the command line tools but, using the
1948 # section 3 of LGPLv2.1, GNU getopt_long can be handled as GPLv2 too.
1949 # Thus GPLv2 should be enough here.
1950 install(FILES AUTHORS
1951               COPYING
1952               COPYING.0BSD
1953               COPYING.GPLv2
1954               NEWS
1955               README
1956               THANKS
1957               doc/faq.txt
1958               doc/history.txt
1959               doc/lzma-file-format.txt
1960               doc/xz-file-format.txt
1961         DESTINATION "${CMAKE_INSTALL_DOCDIR}"
1962         COMPONENT Documentation)
1965 #############################################################################
1966 # Tests
1967 #############################################################################
1969 include(CTest)
1971 if(BUILD_TESTING)
1972     set(LIBLZMA_TESTS
1973         test_bcj_exact_size
1974         test_block_header
1975         test_check
1976         test_filter_flags
1977         test_filter_str
1978         test_hardware
1979         test_index
1980         test_index_hash
1981         test_lzip_decoder
1982         test_memlimit
1983         test_stream_flags
1984         test_vli
1985     )
1987     foreach(TEST IN LISTS LIBLZMA_TESTS)
1988         add_executable("${TEST}" "tests/${TEST}.c")
1990         target_include_directories("${TEST}" PRIVATE
1991             src/common
1992             src/liblzma/api
1993             src/liblzma
1994         )
1996         target_link_libraries("${TEST}" PRIVATE liblzma)
1998         # Put the test programs into their own subdirectory so they don't
1999         # pollute the top-level dir which might contain xz and xzdec.
2000         set_target_properties("${TEST}" PROPERTIES
2001             RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/tests_bin"
2002         )
2004         add_test(NAME "${TEST}"
2005                  COMMAND "${CMAKE_CURRENT_BINARY_DIR}/tests_bin/${TEST}"
2006         )
2008         # Set srcdir environment variable so that the tests find their
2009         # input files from the source tree.
2010         #
2011         # Set the return code for skipped tests to match Automake convention.
2012         set_tests_properties("${TEST}" PROPERTIES
2013             ENVIRONMENT "srcdir=${CMAKE_CURRENT_SOURCE_DIR}/tests"
2014             SKIP_RETURN_CODE 77
2015         )
2016     endforeach()
2018     if(UNIX AND HAVE_DECODERS)
2019         file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_scripts")
2021         add_test(NAME test_scripts.sh
2022             COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_scripts.sh" ".."
2023             WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_scripts"
2024         )
2026         set_tests_properties(test_scripts.sh PROPERTIES
2027             ENVIRONMENT "srcdir=${CMAKE_CURRENT_SOURCE_DIR}/tests"
2028             SKIP_RETURN_CODE 77
2029         )
2030     endif()
2031 endif()