Translations: Update the Hungarian translation.
[xz.git] / CMakeLists.txt
blobb7047dc0582a755395019e31abbb33ee5d594407
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 # windres from GNU binutils can be tricky with command line arguments
162 # that contain spaces or other funny characters. Unfortunately we need
163 # a space in PACKAGE_NAME. Using \x20 to encode the US-ASCII space seems
164 # to work in both cmd.exe and /bin/sh.
166 # However, even \x20 isn't enough in all situations, resulting in
167 # "syntax error" from windres. Using --use-temp-file prevents windres
168 # from using popen() and this seems to fix the problem.
170 # llvm-windres from Clang/LLVM 16.0.6 and older: The \x20 results
171 # in "XZx20Utils" in the compiled binary. The option --use-temp-file
172 # makes no difference.
174 # llvm-windres 17.0.0 and later: It emulates GNU windres more accurately, so
175 # the workarounds used with GNU windres must be used with llvm-windres too.
177 # CMake 3.27 doesn't have CMAKE_RC_COMPILER_ID so we rely on
178 # CMAKE_C_COMPILER_ID.
179 if((MINGW OR CYGWIN OR MSYS) AND (
180         NOT CMAKE_C_COMPILER_ID STREQUAL "Clang" OR
181         CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL "17"))
182     # Use workarounds with GNU windres and llvm-windres >= 17.0.0. The \x20
183     # in PACKAGE_NAME_DEFINITION works with gcc and clang too so we don't need
184     # to worry how to pass different flags to windres and the C compiler.
185     # Keep the original PACKAGE_NAME intact for generation of liblzma.pc.
186     string(APPEND CMAKE_RC_FLAGS " --use-temp-file")
187     string(REPLACE " " "\\x20" PACKAGE_NAME_DEFINITION "${PACKAGE_NAME}")
188 else()
189     # Elsewhere a space is safe. This also keeps things compatible with
190     # EBCDIC in case CMake-based build is ever done on such a system.
191     set(PACKAGE_NAME_DEFINITION "${PACKAGE_NAME}")
192 endif()
194 # Definitions common to all targets:
195 add_compile_definitions(
196     # Package info:
197     PACKAGE_NAME="${PACKAGE_NAME_DEFINITION}"
198     PACKAGE_BUGREPORT="${PACKAGE_BUGREPORT}"
199     PACKAGE_URL="${PACKAGE_URL}"
201     # Standard headers and types are available:
202     HAVE_STDBOOL_H
203     HAVE__BOOL
204     HAVE_STDINT_H
205     HAVE_INTTYPES_H
207     # Always enable CRC32 since liblzma should never build without it.
208     HAVE_CHECK_CRC32
210     # Disable assert() checks when no build type has been specified. Non-empty
211     # build types like "Release" and "Debug" handle this by default.
212     $<$<CONFIG:>:NDEBUG>
216 ######################
217 # System definitions #
218 ######################
220 # _GNU_SOURCE and such definitions. This specific macro is special since
221 # it also adds the definitions to CMAKE_REQUIRED_DEFINITIONS.
222 tuklib_use_system_extensions(ALL)
224 # Check for large file support. It's required on some 32-bit platforms and
225 # even on 64-bit MinGW-w64 to get 64-bit off_t. This can be forced off on
226 # the CMake command line if needed: -DLARGE_FILE_SUPPORT=OFF
227 tuklib_large_file_support(ALL)
229 # This is needed by liblzma and xz.
230 tuklib_integer(ALL)
232 # This is used for liblzma.pc generation to add -lrt if needed.
233 set(LIBS)
235 # Check for clock_gettime(). Do this before checking for threading so
236 # that we know there if CLOCK_MONOTONIC is available.
237 check_symbol_exists(clock_gettime time.h HAVE_CLOCK_GETTIME)
239 if(NOT HAVE_CLOCK_GETTIME)
240     # With glibc <= 2.17 or Solaris 10 this needs librt.
241     # Add librt for the next check for HAVE_CLOCK_GETTIME. If it is
242     # found after including the library, we know that librt is required.
243     list(INSERT CMAKE_REQUIRED_LIBRARIES 0 rt)
244     check_symbol_exists(clock_gettime time.h HAVE_CLOCK_GETTIME_LIBRT)
246     # If it was found now, add librt to all targets and keep it in
247     # CMAKE_REQUIRED_LIBRARIES for further tests too.
248     if(HAVE_CLOCK_GETTIME_LIBRT)
249         link_libraries(rt)
250         set(LIBS "-lrt") # For liblzma.pc
251     else()
252         list(REMOVE_AT CMAKE_REQUIRED_LIBRARIES 0)
253     endif()
254 endif()
256 if(HAVE_CLOCK_GETTIME OR HAVE_CLOCK_GETTIME_LIBRT)
257     add_compile_definitions(HAVE_CLOCK_GETTIME)
259     # Check if CLOCK_MONOTONIC is available for clock_gettime().
260     check_symbol_exists(CLOCK_MONOTONIC time.h HAVE_CLOCK_MONOTONIC)
261     tuklib_add_definition_if(ALL HAVE_CLOCK_MONOTONIC)
262 endif()
264 # Translation support requires CMake 3.20 because it added the Intl::Intl
265 # target so we don't need to play with the individual variables.
267 # The defintion ENABLE_NLS is added only to those targets that use it, thus
268 # it's not done here. (xz has translations, xzdec doesn't.)
269 if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.20")
270     find_package(Intl)
271     find_package(Gettext)
272     if(Intl_FOUND)
273         option(ENABLE_NLS "Native Language Support (translated messages)" ON)
275         # The *installed* name of the translation files is "xz.mo".
276         set(TRANSLATION_DOMAIN "xz")
277     endif()
278 endif()
280 # Options for new enough GCC or Clang on any arch or operating system:
281 if(CMAKE_C_COMPILER_ID MATCHES GNU|Clang)
282     # configure.ac has a long list but it won't be copied here:
283     add_compile_options(-Wall -Wextra)
284 endif()
287 #############################################################################
288 # liblzma
289 #############################################################################
291 option(BUILD_SHARED_LIBS "Build liblzma as a shared library instead of static")
293 add_library(liblzma
294     src/common/mythread.h
295     src/common/sysdefs.h
296     src/common/tuklib_common.h
297     src/common/tuklib_config.h
298     src/common/tuklib_integer.h
299     src/common/tuklib_physmem.c
300     src/common/tuklib_physmem.h
301     src/liblzma/api/lzma.h
302     src/liblzma/api/lzma/base.h
303     src/liblzma/api/lzma/bcj.h
304     src/liblzma/api/lzma/block.h
305     src/liblzma/api/lzma/check.h
306     src/liblzma/api/lzma/container.h
307     src/liblzma/api/lzma/delta.h
308     src/liblzma/api/lzma/filter.h
309     src/liblzma/api/lzma/hardware.h
310     src/liblzma/api/lzma/index.h
311     src/liblzma/api/lzma/index_hash.h
312     src/liblzma/api/lzma/lzma12.h
313     src/liblzma/api/lzma/stream_flags.h
314     src/liblzma/api/lzma/version.h
315     src/liblzma/api/lzma/vli.h
316     src/liblzma/check/check.c
317     src/liblzma/check/check.h
318     src/liblzma/check/crc_common.h
319     src/liblzma/check/crc_x86_clmul.h
320     src/liblzma/check/crc32_arm64.h
321     src/liblzma/common/block_util.c
322     src/liblzma/common/common.c
323     src/liblzma/common/common.h
324     src/liblzma/common/easy_preset.c
325     src/liblzma/common/easy_preset.h
326     src/liblzma/common/filter_common.c
327     src/liblzma/common/filter_common.h
328     src/liblzma/common/hardware_physmem.c
329     src/liblzma/common/index.c
330     src/liblzma/common/index.h
331     src/liblzma/common/memcmplen.h
332     src/liblzma/common/stream_flags_common.c
333     src/liblzma/common/stream_flags_common.h
334     src/liblzma/common/string_conversion.c
335     src/liblzma/common/vli_size.c
338 target_include_directories(liblzma PRIVATE
339     src/liblzma/api
340     src/liblzma/common
341     src/liblzma/check
342     src/liblzma/lz
343     src/liblzma/rangecoder
344     src/liblzma/lzma
345     src/liblzma/delta
346     src/liblzma/simple
347     src/common
351 ######################
352 # Size optimizations #
353 ######################
355 option(ENABLE_SMALL "Reduce code size at expense of speed. \
356 This may be useful together with CMAKE_BUILD_TYPE=MinSizeRel.")
358 if(ENABLE_SMALL)
359     add_compile_definitions(HAVE_SMALL)
360 endif()
363 ##########
364 # Checks #
365 ##########
367 set(ADDITIONAL_SUPPORTED_CHECKS crc64 sha256)
369 set(ADDITIONAL_CHECK_TYPES "${ADDITIONAL_SUPPORTED_CHECKS}" CACHE STRING
370     "Additional check types to support (crc32 is always built)")
372 foreach(CHECK IN LISTS ADDITIONAL_CHECK_TYPES)
373     if(NOT CHECK IN_LIST ADDITIONAL_SUPPORTED_CHECKS)
374         message(FATAL_ERROR "'${CHECK}' is not a supported check type")
375     endif()
376 endforeach()
378 if(ENABLE_SMALL)
379     target_sources(liblzma PRIVATE src/liblzma/check/crc32_small.c)
380 else()
381     target_sources(liblzma PRIVATE
382         src/liblzma/check/crc32_fast.c
383         src/liblzma/check/crc32_table.c
384         src/liblzma/check/crc32_table_be.h
385         src/liblzma/check/crc32_table_le.h
386     )
387 endif()
389 if("crc64" IN_LIST ADDITIONAL_CHECK_TYPES)
390     add_compile_definitions("HAVE_CHECK_CRC64")
392     if(ENABLE_SMALL)
393         target_sources(liblzma PRIVATE src/liblzma/check/crc64_small.c)
394     else()
395         target_sources(liblzma PRIVATE
396             src/liblzma/check/crc64_fast.c
397             src/liblzma/check/crc64_table.c
398             src/liblzma/check/crc64_table_be.h
399             src/liblzma/check/crc64_table_le.h
400         )
401     endif()
402 endif()
404 if("sha256" IN_LIST ADDITIONAL_CHECK_TYPES)
405     add_compile_definitions("HAVE_CHECK_SHA256")
406     target_sources(liblzma PRIVATE src/liblzma/check/sha256.c)
407 endif()
410 #################
411 # Match finders #
412 #################
414 set(SUPPORTED_MATCH_FINDERS hc3 hc4 bt2 bt3 bt4)
416 set(MATCH_FINDERS "${SUPPORTED_MATCH_FINDERS}" CACHE STRING
417     "Match finders to support (at least one is required for LZMA1 or LZMA2)")
419 foreach(MF IN LISTS MATCH_FINDERS)
420     if(MF IN_LIST SUPPORTED_MATCH_FINDERS)
421         string(TOUPPER "${MF}" MF_UPPER)
422         add_compile_definitions("HAVE_MF_${MF_UPPER}")
423     else()
424         message(FATAL_ERROR "'${MF}' is not a supported match finder")
425     endif()
426 endforeach()
429 #############
430 # Threading #
431 #############
433 # Supported threading methods:
434 # ON    - autodetect the best threading method. The autodetection will
435 #         prefer Windows threading (win95 or vista) over posix if both are
436 #         available. vista threads will be used over win95 unless it is a
437 #         32-bit build.
438 # OFF   - Disable threading.
439 # posix - Use posix threading (pthreads), or throw an error if not available.
440 # win95 - Use Windows win95 threading, or throw an error if not available.
441 # vista - Use Windows vista threading, or throw an error if not available.
442 set(SUPPORTED_THREADING_METHODS ON OFF posix win95 vista)
444 set(ENABLE_THREADS ON CACHE STRING
445     "Threading method: Set to 'ON' to autodetect, 'OFF' to disable threading.")
447 # Create dropdown in CMake GUI since only 1 threading method is possible
448 # to select in a build.
449 set_property(CACHE ENABLE_THREADS
450              PROPERTY STRINGS "${SUPPORTED_THREADING_METHODS}")
452 # This is a flag variable set when win95 threads are used. We must ensure
453 # the combination of enable_small and win95 threads is not used without a
454 # compiler supporting attribute __constructor__.
455 set(USE_WIN95_THREADS OFF)
457 # This is a flag variable set when posix threads (pthreads) are used.
458 # It's needed when creating liblzma-config.cmake where dependency on
459 # Threads::Threads is only needed with pthreads.
460 set(USE_POSIX_THREADS OFF)
462 if(NOT ENABLE_THREADS IN_LIST SUPPORTED_THREADING_METHODS)
463     message(FATAL_ERROR "'${ENABLE_THREADS}' is not a supported "
464                         "threading method")
465 endif()
467 if(ENABLE_THREADS)
468     # Also set THREADS_PREFER_PTHREAD_FLAG since the flag has no effect
469     # for Windows threading.
470     set(THREADS_PREFER_PTHREAD_FLAG TRUE)
471     find_package(Threads REQUIRED)
473     # If both Windows and posix threading are available, prefer Windows.
474     # Note that on Cygwin CMAKE_USE_WIN32_THREADS_INIT is false.
475     if(CMAKE_USE_WIN32_THREADS_INIT AND NOT ENABLE_THREADS STREQUAL "posix")
476         if(ENABLE_THREADS STREQUAL "win95"
477                 OR (ENABLE_THREADS STREQUAL "ON"
478                     AND CMAKE_SIZEOF_VOID_P EQUAL 4))
479             # Use Windows 95 (and thus XP) compatible threads.
480             # This avoids use of features that were added in
481             # Windows Vista. This is used for 32-bit x86 builds for
482             # compatibility reasons since it makes no measurable difference
483             # in performance compared to Vista threads.
484             set(USE_WIN95_THREADS ON)
485             add_compile_definitions(MYTHREAD_WIN95)
486         else()
487             add_compile_definitions(MYTHREAD_VISTA)
488         endif()
489     elseif(CMAKE_USE_PTHREADS_INIT)
490         if(ENABLE_THREADS STREQUAL "posix" OR ENABLE_THREADS STREQUAL "ON")
491             # The threading library only needs to be explicitly linked
492             # for posix threads, so this is needed for creating
493             # liblzma-config.cmake later.
494             set(USE_POSIX_THREADS ON)
496             target_link_libraries(liblzma Threads::Threads)
497             add_compile_definitions(MYTHREAD_POSIX)
499             # Check if pthread_condattr_setclock() exists to
500             # use CLOCK_MONOTONIC.
501             if(HAVE_CLOCK_MONOTONIC)
502                 list(INSERT CMAKE_REQUIRED_LIBRARIES 0
503                      "${CMAKE_THREAD_LIBS_INIT}")
504                 check_symbol_exists(pthread_condattr_setclock pthread.h
505                                     HAVE_PTHREAD_CONDATTR_SETCLOCK)
506                 tuklib_add_definition_if(ALL HAVE_PTHREAD_CONDATTR_SETCLOCK)
507             endif()
508         else()
509             message(SEND_ERROR
510                     "Windows threading method was requested but a compatible "
511                     "library could not be found")
512         endif()
513     else()
514         message(SEND_ERROR "No supported threading library found")
515     endif()
517     target_sources(liblzma PRIVATE
518         src/common/tuklib_cpucores.c
519         src/common/tuklib_cpucores.h
520         src/liblzma/common/hardware_cputhreads.c
521         src/liblzma/common/outqueue.c
522         src/liblzma/common/outqueue.h
523     )
524 endif()
527 ############
528 # Encoders #
529 ############
531 set(SIMPLE_FILTERS
532     x86
533     arm
534     armthumb
535     arm64
536     powerpc
537     ia64
538     sparc
539     riscv
542 # The SUPPORTED_FILTERS are shared between Encoders and Decoders
543 # since only lzip does not appear in both lists. lzip is a special
544 # case anyway, so it is handled separately in the Decoders section.
545 set(SUPPORTED_FILTERS
546     lzma1
547     lzma2
548     delta
549     "${SIMPLE_FILTERS}"
552 set(ENCODERS "${SUPPORTED_FILTERS}" CACHE STRING "Encoders to support")
554 # If LZMA2 is enabled, then LZMA1 must also be enabled.
555 if(NOT "lzma1" IN_LIST ENCODERS AND "lzma2" IN_LIST ENCODERS)
556     message(FATAL_ERROR "LZMA2 encoder requires that LZMA1 is also enabled")
557 endif()
559 # If LZMA1 is enabled, then at least one match finder must be enabled.
560 if(MATCH_FINDERS STREQUAL "" AND "lzma1" IN_LIST ENCODERS)
561     message(FATAL_ERROR "At least 1 match finder is required for an "
562                         "LZ-based encoder")
563 endif()
565 set(HAVE_DELTA_CODER OFF)
566 set(SIMPLE_ENCODERS OFF)
567 set(HAVE_ENCODERS OFF)
569 foreach(ENCODER IN LISTS ENCODERS)
570     if(ENCODER IN_LIST SUPPORTED_FILTERS)
571         set(HAVE_ENCODERS ON)
573         if(NOT SIMPLE_ENCODERS AND ENCODER IN_LIST SIMPLE_FILTERS)
574             set(SIMPLE_ENCODERS ON)
575         endif()
577         string(TOUPPER "${ENCODER}" ENCODER_UPPER)
578         add_compile_definitions("HAVE_ENCODER_${ENCODER_UPPER}")
579     else()
580         message(FATAL_ERROR "'${ENCODER}' is not a supported encoder")
581     endif()
582 endforeach()
584 if(HAVE_ENCODERS)
585     add_compile_definitions(HAVE_ENCODERS)
587     target_sources(liblzma PRIVATE
588         src/liblzma/common/alone_encoder.c
589         src/liblzma/common/block_buffer_encoder.c
590         src/liblzma/common/block_buffer_encoder.h
591         src/liblzma/common/block_encoder.c
592         src/liblzma/common/block_encoder.h
593         src/liblzma/common/block_header_encoder.c
594         src/liblzma/common/easy_buffer_encoder.c
595         src/liblzma/common/easy_encoder.c
596         src/liblzma/common/easy_encoder_memusage.c
597         src/liblzma/common/filter_buffer_encoder.c
598         src/liblzma/common/filter_encoder.c
599         src/liblzma/common/filter_encoder.h
600         src/liblzma/common/filter_flags_encoder.c
601         src/liblzma/common/index_encoder.c
602         src/liblzma/common/index_encoder.h
603         src/liblzma/common/stream_buffer_encoder.c
604         src/liblzma/common/stream_encoder.c
605         src/liblzma/common/stream_flags_encoder.c
606         src/liblzma/common/vli_encoder.c
607     )
609     if(ENABLE_THREADS)
610         target_sources(liblzma PRIVATE
611             src/liblzma/common/stream_encoder_mt.c
612         )
613     endif()
615     if(SIMPLE_ENCODERS)
616         target_sources(liblzma PRIVATE
617             src/liblzma/simple/simple_encoder.c
618             src/liblzma/simple/simple_encoder.h
619         )
620     endif()
622     if("lzma1" IN_LIST ENCODERS)
623         target_sources(liblzma PRIVATE
624             src/liblzma/lzma/lzma_encoder.c
625             src/liblzma/lzma/lzma_encoder.h
626             src/liblzma/lzma/lzma_encoder_optimum_fast.c
627             src/liblzma/lzma/lzma_encoder_optimum_normal.c
628             src/liblzma/lzma/lzma_encoder_private.h
629             src/liblzma/lzma/fastpos.h
630             src/liblzma/lz/lz_encoder.c
631             src/liblzma/lz/lz_encoder.h
632             src/liblzma/lz/lz_encoder_hash.h
633             src/liblzma/lz/lz_encoder_hash_table.h
634             src/liblzma/lz/lz_encoder_mf.c
635             src/liblzma/rangecoder/price.h
636             src/liblzma/rangecoder/price_table.c
637             src/liblzma/rangecoder/range_encoder.h
638         )
640         if(NOT ENABLE_SMALL)
641             target_sources(liblzma PRIVATE src/liblzma/lzma/fastpos_table.c)
642         endif()
643     endif()
645     if("lzma2" IN_LIST ENCODERS)
646         target_sources(liblzma PRIVATE
647             src/liblzma/lzma/lzma2_encoder.c
648             src/liblzma/lzma/lzma2_encoder.h
649         )
650     endif()
652     if("delta" IN_LIST ENCODERS)
653         set(HAVE_DELTA_CODER ON)
654         target_sources(liblzma PRIVATE
655             src/liblzma/delta/delta_encoder.c
656             src/liblzma/delta/delta_encoder.h
657         )
658     endif()
659 endif()
662 ############
663 # Decoders #
664 ############
666 set(DECODERS "${SUPPORTED_FILTERS}" CACHE STRING "Decoders to support")
668 set(SIMPLE_DECODERS OFF)
669 set(HAVE_DECODERS OFF)
671 foreach(DECODER IN LISTS DECODERS)
672     if(DECODER IN_LIST SUPPORTED_FILTERS)
673         set(HAVE_DECODERS ON)
675         if(NOT SIMPLE_DECODERS AND DECODER IN_LIST SIMPLE_FILTERS)
676             set(SIMPLE_DECODERS ON)
677         endif()
679         string(TOUPPER "${DECODER}" DECODER_UPPER)
680         add_compile_definitions("HAVE_DECODER_${DECODER_UPPER}")
681     else()
682         message(FATAL_ERROR "'${DECODER}' is not a supported decoder")
683     endif()
684 endforeach()
686 if(HAVE_DECODERS)
687     add_compile_definitions(HAVE_DECODERS)
689     target_sources(liblzma PRIVATE
690         src/liblzma/common/alone_decoder.c
691         src/liblzma/common/alone_decoder.h
692         src/liblzma/common/auto_decoder.c
693         src/liblzma/common/block_buffer_decoder.c
694         src/liblzma/common/block_decoder.c
695         src/liblzma/common/block_decoder.h
696         src/liblzma/common/block_header_decoder.c
697         src/liblzma/common/easy_decoder_memusage.c
698         src/liblzma/common/file_info.c
699         src/liblzma/common/filter_buffer_decoder.c
700         src/liblzma/common/filter_decoder.c
701         src/liblzma/common/filter_decoder.h
702         src/liblzma/common/filter_flags_decoder.c
703         src/liblzma/common/index_decoder.c
704         src/liblzma/common/index_decoder.h
705         src/liblzma/common/index_hash.c
706         src/liblzma/common/stream_buffer_decoder.c
707         src/liblzma/common/stream_decoder.c
708         src/liblzma/common/stream_flags_decoder.c
709         src/liblzma/common/stream_decoder.h
710         src/liblzma/common/vli_decoder.c
711     )
713     if(ENABLE_THREADS)
714         target_sources(liblzma PRIVATE
715             src/liblzma/common/stream_decoder_mt.c
716         )
717     endif()
719     if(SIMPLE_DECODERS)
720         target_sources(liblzma PRIVATE
721             src/liblzma/simple/simple_decoder.c
722             src/liblzma/simple/simple_decoder.h
723         )
724     endif()
726     if("lzma1" IN_LIST DECODERS)
727         target_sources(liblzma PRIVATE
728             src/liblzma/lzma/lzma_decoder.c
729             src/liblzma/lzma/lzma_decoder.h
730             src/liblzma/rangecoder/range_decoder.h
731             src/liblzma/lz/lz_decoder.c
732             src/liblzma/lz/lz_decoder.h
733         )
734     endif()
736     if("lzma2" IN_LIST DECODERS)
737         target_sources(liblzma PRIVATE
738             src/liblzma/lzma/lzma2_decoder.c
739             src/liblzma/lzma/lzma2_decoder.h
740         )
741     endif()
743     if("delta" IN_LIST DECODERS)
744         set(HAVE_DELTA_CODER ON)
745         target_sources(liblzma PRIVATE
746             src/liblzma/delta/delta_decoder.c
747             src/liblzma/delta/delta_decoder.h
748         )
749     endif()
750 endif()
752 # Some sources must appear if the filter is configured as either
753 # an encoder or decoder.
754 if("lzma1" IN_LIST ENCODERS OR "lzma1" IN_LIST DECODERS)
755     target_sources(liblzma PRIVATE
756         src/liblzma/rangecoder/range_common.h
757         src/liblzma/lzma/lzma_encoder_presets.c
758         src/liblzma/lzma/lzma_common.h
759     )
760 endif()
762 if(HAVE_DELTA_CODER)
763     target_sources(liblzma PRIVATE
764         src/liblzma/delta/delta_common.c
765         src/liblzma/delta/delta_common.h
766         src/liblzma/delta/delta_private.h
767     )
768 endif()
770 if(SIMPLE_ENCODERS OR SIMPLE_DECODERS)
771     target_sources(liblzma PRIVATE
772         src/liblzma/simple/simple_coder.c
773         src/liblzma/simple/simple_coder.h
774         src/liblzma/simple/simple_private.h
775     )
776 endif()
778 foreach(SIMPLE_CODER IN LISTS SIMPLE_FILTERS)
779     if(SIMPLE_CODER IN_LIST ENCODERS OR SIMPLE_CODER IN_LIST DECODERS)
780         target_sources(liblzma PRIVATE "src/liblzma/simple/${SIMPLE_CODER}.c")
781     endif()
782 endforeach()
785 #############
786 # MicroLZMA #
787 #############
789 option(MICROLZMA_ENCODER
790        "MicroLZMA encoder (needed by specific applications only)" ON)
792 option(MICROLZMA_DECODER
793        "MicroLZMA decoder (needed by specific applications only)" ON)
795 if(MICROLZMA_ENCODER)
796     if(NOT "lzma1" IN_LIST ENCODERS)
797         message(FATAL_ERROR "The LZMA1 encoder is required to support the "
798                             "MicroLZMA encoder")
799     endif()
801     target_sources(liblzma PRIVATE src/liblzma/common/microlzma_encoder.c)
802 endif()
804 if(MICROLZMA_DECODER)
805     if(NOT "lzma1" IN_LIST DECODERS)
806         message(FATAL_ERROR "The LZMA1 decoder is required to support the "
807                             "MicroLZMA decoder")
808     endif()
810     target_sources(liblzma PRIVATE src/liblzma/common/microlzma_decoder.c)
811 endif()
814 #############################
815 # lzip (.lz) format support #
816 #############################
818 option(LZIP_DECODER "Support lzip decoder" ON)
820 if(LZIP_DECODER)
821     # If lzip decoder support is requested, make sure LZMA1 decoder is enabled.
822     if(NOT "lzma1" IN_LIST DECODERS)
823         message(FATAL_ERROR "The LZMA1 decoder is required to support the "
824                             "lzip decoder")
825     endif()
827     add_compile_definitions(HAVE_LZIP_DECODER)
829     target_sources(liblzma PRIVATE
830         src/liblzma/common/lzip_decoder.c
831         src/liblzma/common/lzip_decoder.h
832     )
833 endif()
836 ##############
837 # Sandboxing #
838 ##############
840 # ON        Use sandboxing if a supported method is available in the OS.
841 # OFF       Disable sandboxing.
842 # capsicum  Require Capsicum (FreeBSD >= 10.2) and fail if not found.
843 # pledge    Require pledge(2) (OpenBSD >= 5.9) and fail if not found.
844 # landlock  Require Landlock (Linux >= 5.13) and fail if not found.
845 set(SUPPORTED_SANDBOX_METHODS ON OFF capsicum pledge landlock)
847 set(ENABLE_SANDBOX ON CACHE STRING
848     "Sandboxing method to use in 'xz', 'xzdec', and 'lzmadec'")
850 set_property(CACHE ENABLE_SANDBOX
851                 PROPERTY STRINGS "${SUPPORTED_SANDBOX_METHODS}")
853 if(NOT ENABLE_SANDBOX IN_LIST SUPPORTED_SANDBOX_METHODS)
854     message(FATAL_ERROR "'${ENABLE_SANDBOX}' is not a supported "
855                         "sandboxing method")
856 endif()
858 # When autodetecting, the search order is fixed and we must not find
859 # more than one method.
860 if(ENABLE_SANDBOX STREQUAL "OFF")
861     set(SANDBOX_FOUND ON)
862 else()
863     set(SANDBOX_FOUND OFF)
864 endif()
866 # Since xz and xzdec can both use sandboxing, the compile definition needed
867 # to use the sandbox must be added to both targets.
868 set(SANDBOX_COMPILE_DEFINITION OFF)
870 # Sandboxing: Capsicum
871 if(NOT SANDBOX_FOUND AND ENABLE_SANDBOX MATCHES "^ON$|^capsicum$")
872     check_symbol_exists(cap_rights_limit sys/capsicum.h
873                         HAVE_CAP_RIGHTS_LIMIT)
874     if(HAVE_CAP_RIGHTS_LIMIT)
875         set(SANDBOX_COMPILE_DEFINITION "HAVE_CAP_RIGHTS_LIMIT")
876         set(SANDBOX_FOUND ON)
877     endif()
878 endif()
880 # Sandboxing: pledge(2)
881 if(NOT SANDBOX_FOUND AND ENABLE_SANDBOX MATCHES "^ON$|^pledge$")
882     check_symbol_exists(pledge unistd.h HAVE_PLEDGE)
883     if(HAVE_PLEDGE)
884         set(SANDBOX_COMPILE_DEFINITION "HAVE_PLEDGE")
885         set(SANDBOX_FOUND ON)
886     endif()
887 endif()
889 # Sandboxing: Landlock
890 if(NOT SANDBOX_FOUND AND ENABLE_SANDBOX MATCHES "^ON$|^landlock$")
891     check_include_file(linux/landlock.h HAVE_LINUX_LANDLOCK_H)
893     if(HAVE_LINUX_LANDLOCK_H)
894         set(SANDBOX_COMPILE_DEFINITION "HAVE_LINUX_LANDLOCK_H")
895         set(SANDBOX_FOUND ON)
897         # Of our three sandbox methods, only Landlock is incompatible
898         # with -fsanitize. FreeBSD 13.2 with Capsicum was tested with
899         # -fsanitize=address,undefined and had no issues. OpenBSD (as
900         # of version 7.4) has minimal support for process instrumentation.
901         # OpenBSD does not distribute the additional libraries needed
902         # (libasan, libubsan, etc.) with GCC or Clang needed for runtime
903         # sanitization support and instead only support
904         # -fsanitize-minimal-runtime for minimal undefined behavior
905         # sanitization. This minimal support is compatible with our use
906         # of the Pledge sandbox. So only Landlock will result in a
907         # build that cannot compress or decompress a single file to
908         # standard out.
909         if(CMAKE_C_FLAGS MATCHES "-fsanitize=")
910             message(SEND_ERROR
911                     "CMAKE_C_FLAGS or the environment variable CFLAGS "
912                     "contains '-fsanitize=' which is incompatible "
913                     "with Landlock sandboxing. Use -DENABLE_SANDBOX=OFF "
914                     "as an argument to 'cmake' when using '-fsanitize'.")
915         endif()
916     endif()
917 endif()
919 if(NOT SANDBOX_FOUND AND NOT ENABLE_SANDBOX MATCHES "^ON$|^OFF$")
920     message(SEND_ERROR "ENABLE_SANDBOX=${ENABLE_SANDBOX} was used but "
921                         "support for the sandboxing method wasn't found.")
922 endif()
926 # Put the tuklib functions under the lzma_ namespace.
927 target_compile_definitions(liblzma PRIVATE TUKLIB_SYMBOL_PREFIX=lzma_)
928 tuklib_cpucores(liblzma)
929 tuklib_physmem(liblzma)
931 # While liblzma can be built without tuklib_cpucores or tuklib_physmem
932 # modules, the liblzma API functions lzma_cputhreads() and lzma_physmem()
933 # will then be useless (which isn't too bad but still unfortunate). Since
934 # I expect the CMake-based builds to be only used on systems that are
935 # supported by these tuklib modules, problems with these tuklib modules
936 # are considered a hard error for now. This hopefully helps to catch bugs
937 # in the CMake versions of the tuklib checks.
938 if(NOT TUKLIB_CPUCORES_FOUND OR NOT TUKLIB_PHYSMEM_FOUND)
939     # Use SEND_ERROR instead of FATAL_ERROR. If someone reports a bug,
940     # seeing the results of the remaining checks can be useful too.
941     message(SEND_ERROR
942             "tuklib_cpucores() or tuklib_physmem() failed. "
943             "Unless you really are building for a system where these "
944             "modules are not supported (unlikely), this is a bug in the "
945             "included cmake/tuklib_*.cmake files that should be fixed. "
946             "To build anyway, edit this CMakeLists.txt to ignore this error.")
947 endif()
949 # Check for __attribute__((__constructor__)) support.
950 # This needs -Werror because some compilers just warn
951 # about this being unsupported.
952 cmake_push_check_state()
953 set(CMAKE_REQUIRED_FLAGS "-Werror")
954 check_c_source_compiles("
955         __attribute__((__constructor__))
956         static void my_constructor_func(void) { return; }
957         int main(void) { return 0; }
958     "
959     HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
960 cmake_pop_check_state()
961 tuklib_add_definition_if(liblzma HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
963 # The Win95 threading lacks a thread-safe one-time initialization function.
964 # The one-time initialization is needed for crc32_small.c and crc64_small.c
965 # create the CRC tables. So if small mode is enabled, the threading mode is
966 # win95, and the compiler does not support attribute constructor, then we
967 # would end up with a multithreaded build that is thread-unsafe. As a
968 # result this configuration is not allowed.
969 if(USE_WIN95_THREADS AND ENABLE_SMALL AND NOT HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
970     message(SEND_ERROR "Threading method win95 and ENABLE_SMALL "
971                         "cannot be used at the same time with a compiler "
972                         "that doesn't support "
973                         "__attribute__((__constructor__))")
974 endif()
977 # Check for __attribute__((__ifunc__())) support.
978 # Supported values for USE_ATTR_IFUNC:
980 # auto (default) - Detect ifunc support with a compile test.
981 # ON             - Always enable ifunc.
982 # OFF            - Disable ifunc usage.
983 set(USE_ATTR_IFUNC "auto" CACHE STRING "Use __attribute__((__ifunc__())).")
985 set(SUPPORTED_USE_ATTR_IFUNC auto ON OFF)
987 if(NOT USE_ATTR_IFUNC IN_LIST SUPPORTED_USE_ATTR_IFUNC)
988     message(FATAL_ERROR "'${USE_ATTR_IFUNC}' is not a supported value for"
989                         "USE_ATTR_IFUNC")
990 endif()
992 # When USE_ATTR_IFUNC is 'auto', allow the use of __attribute__((__ifunc__()))
993 # if compiler support is detected and we are building for GNU/Linux (glibc)
994 # or FreeBSD. uClibc and musl don't support ifunc in their dynamic linkers
995 # but some compilers still accept the attribute when compiling for these
996 # C libraries, which results in broken binaries. That's why we need to
997 # check which libc is being used.
998 if(USE_ATTR_IFUNC STREQUAL "auto")
999     cmake_push_check_state()
1000     set(CMAKE_REQUIRED_FLAGS "-Werror")
1002     check_c_source_compiles("
1003             /*
1004              * Force a compilation error when not using glibc on Linux
1005              * or if we are not using FreeBSD. uClibc will define
1006              * __GLIBC__ but does not support ifunc, so we must have
1007              * an extra check to disable with uClibc.
1008              */
1009             #if defined(__linux__)
1010             #   include <features.h>
1011             #   if !defined(__GLIBC__) || defined(__UCLIBC__)
1012             compile error
1013             #   endif
1014             #elif !defined(__FreeBSD__)
1015             compile error
1016             #endif
1018             static void func(void) { return; }
1019             static void (*resolve_func(void)) (void) { return func; }
1020             void func_ifunc(void)
1021                     __attribute__((__ifunc__(\"resolve_func\")));
1022             int main(void) { return 0; }
1023             /*
1024              * 'clang -Wall' incorrectly warns that resolve_func is
1025              * unused (-Wunused-function). Correct assembly output is
1026              * still produced. This problem exists at least in Clang
1027              * versions 4 to 17. The following silences the bogus warning:
1028              */
1029             void make_clang_quiet(void);
1030             void make_clang_quiet(void) { resolve_func()(); }
1031         "
1032         SYSTEM_SUPPORTS_IFUNC)
1034         cmake_pop_check_state()
1035 endif()
1037 if(USE_ATTR_IFUNC STREQUAL "ON" OR SYSTEM_SUPPORTS_IFUNC)
1038     tuklib_add_definitions(liblzma HAVE_FUNC_ATTRIBUTE_IFUNC)
1040     if(CMAKE_C_FLAGS MATCHES "-fsanitize=")
1041         message(SEND_ERROR
1042                 "CMAKE_C_FLAGS or the environment variable CFLAGS "
1043                 "contains '-fsanitize=' which is incompatible "
1044                 "with ifunc. Use -DUSE_ATTR_IFUNC=OFF "
1045                 "as an argument to 'cmake' when using '-fsanitize'.")
1046     endif()
1047 endif()
1049 # cpuid.h
1050 check_include_file(cpuid.h HAVE_CPUID_H)
1051 tuklib_add_definition_if(liblzma HAVE_CPUID_H)
1053 # immintrin.h:
1054 check_include_file(immintrin.h HAVE_IMMINTRIN_H)
1055 if(HAVE_IMMINTRIN_H)
1056     target_compile_definitions(liblzma PRIVATE HAVE_IMMINTRIN_H)
1058     # SSE2 intrinsics:
1059     check_c_source_compiles("
1060             #include <immintrin.h>
1061             int main(void)
1062             {
1063                 __m128i x = { 0 };
1064                 _mm_movemask_epi8(x);
1065                 return 0;
1066             }
1067         "
1068         HAVE__MM_MOVEMASK_EPI8)
1069     tuklib_add_definition_if(liblzma HAVE__MM_MOVEMASK_EPI8)
1071     # CLMUL intrinsic:
1072     option(ALLOW_CLMUL_CRC "Allow carryless multiplication for CRC \
1073 calculation if supported by the system" ON)
1075     if(ALLOW_CLMUL_CRC)
1076         check_c_source_compiles("
1077                 #include <immintrin.h>
1078                 #if defined(__e2k__) && __iset__ < 6
1079                 #   error
1080                 #endif
1081                 #if (defined(__GNUC__) || defined(__clang__)) \
1082                         && !defined(__EDG__)
1083                 __attribute__((__target__(\"ssse3,sse4.1,pclmul\")))
1084                 #endif
1085                 __m128i my_clmul(__m128i a)
1086                 {
1087                     const __m128i b = _mm_set_epi64x(1, 2);
1088                     return _mm_clmulepi64_si128(a, b, 0);
1089                 }
1090                 int main(void) { return 0; }
1091             "
1092             HAVE_USABLE_CLMUL)
1093         tuklib_add_definition_if(liblzma HAVE_USABLE_CLMUL)
1094     endif()
1095 endif()
1097 # ARM64 C Language Extensions define CRC32 functions in arm_acle.h.
1098 # These are supported by at least GCC and Clang which both need
1099 # __attribute__((__target__("+crc"))), unless the needed compiler flags
1100 # are used to support the CRC instruction.
1101 option(ALLOW_ARM64_CRC32 "Allow ARM64 CRC32 instruction if supported by \
1102 the system" ON)
1104 if(ALLOW_ARM64_CRC32)
1105     check_c_source_compiles("
1106             #include <stdint.h>
1108             #ifndef _MSC_VER
1109             #include <arm_acle.h>
1110             #endif
1112             #if (defined(__GNUC__) || defined(__clang__)) && !defined(__EDG__)
1113             __attribute__((__target__(\"+crc\")))
1114             #endif
1115             uint32_t my_crc(uint32_t a, uint64_t b)
1116             {
1117                 return __crc32d(a, b);
1118             }
1119             int main(void) { return 0; }
1120         "
1121         HAVE_ARM64_CRC32)
1123     if(HAVE_ARM64_CRC32)
1124         target_compile_definitions(liblzma PRIVATE HAVE_ARM64_CRC32)
1126         # Check for ARM64 CRC32 instruction runtime detection.
1127         # getauxval() is supported on Linux.
1128         check_symbol_exists(getauxval sys/auxv.h HAVE_GETAUXVAL)
1129         tuklib_add_definition_if(liblzma HAVE_GETAUXVAL)
1131         # elf_aux_info() is supported on FreeBSD.
1132         check_symbol_exists(elf_aux_info sys/auxv.h HAVE_ELF_AUX_INFO)
1133         tuklib_add_definition_if(liblzma HAVE_ELF_AUX_INFO)
1135         # sysctlbyname("hw.optional.armv8_crc32", ...) is supported on Darwin
1136         # (macOS, iOS, etc.). Note that sysctlbyname() is supported on FreeBSD,
1137         # NetBSD, and possibly others too but the string is specific to
1138         # Apple OSes. The C code is responsible for checking
1139         # defined(__APPLE__) before using
1140         # sysctlbyname("hw.optional.armv8_crc32", ...).
1141         check_symbol_exists(sysctlbyname sys/sysctl.h HAVE_SYSCTLBYNAME)
1142         tuklib_add_definition_if(liblzma HAVE_SYSCTLBYNAME)
1143     endif()
1144 endif()
1147 # Symbol visibility support:
1149 # The C_VISIBILITY_PRESET property takes care of adding the compiler
1150 # option -fvisibility=hidden (or equivalent) if and only if it is supported.
1152 # HAVE_VISIBILITY should always be defined to 0 or 1. It tells liblzma
1153 # if __attribute__((__visibility__("default")))
1154 # and __attribute__((__visibility__("hidden"))) are supported.
1155 # Those are useful only when the compiler supports -fvisibility=hidden
1156 # or such option so HAVE_VISIBILITY should be 1 only when both option and
1157 # the attribute support are present. HAVE_VISIBILITY is ignored on Windows
1158 # and Cygwin by the liblzma C code; __declspec(dllexport) is used instead.
1160 # CMake's GenerateExportHeader module is too fancy since liblzma already
1161 # has the necessary macros. Instead, check CMake's internal variable
1162 # CMAKE_C_COMPILE_OPTIONS_VISIBILITY (it's the C-specific variant of
1163 # CMAKE_<LANG>_COMPILE_OPTIONS_VISIBILITY) which contains the compiler
1164 # command line option for visibility support. It's empty or unset when
1165 # visibility isn't supported. (It was added to CMake 2.8.12 in the commit
1166 # 0e9f4bc00c6b26f254e74063e4026ac33b786513 in 2013.) This way we don't
1167 # set HAVE_VISIBILITY to 1 when visibility isn't actually supported.
1168 if(BUILD_SHARED_LIBS AND CMAKE_C_COMPILE_OPTIONS_VISIBILITY)
1169     set_target_properties(liblzma PROPERTIES C_VISIBILITY_PRESET hidden)
1170     target_compile_definitions(liblzma PRIVATE HAVE_VISIBILITY=1)
1171 else()
1172     target_compile_definitions(liblzma PRIVATE HAVE_VISIBILITY=0)
1173 endif()
1175 if(WIN32)
1176     if(BUILD_SHARED_LIBS)
1177         # Add the Windows resource file for liblzma.dll.
1178         target_sources(liblzma PRIVATE src/liblzma/liblzma_w32res.rc)
1180         set_target_properties(liblzma PROPERTIES
1181             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1182         )
1184         # Export the public API symbols with __declspec(dllexport).
1185         target_compile_definitions(liblzma PRIVATE DLL_EXPORT)
1187         if(NOT MSVC)
1188             # Create a DEF file. The linker puts the ordinal numbers there
1189             # too so the output from the linker isn't our final file.
1190             target_link_options(liblzma PRIVATE
1191                                 "-Wl,--output-def,liblzma.def.in")
1193             # Remove the ordinal numbers from the DEF file so that
1194             # no one will create an import library that links by ordinal
1195             # instead of by name. We don't maintain a DEF file so the
1196             # ordinal numbers aren't stable.
1197             add_custom_command(TARGET liblzma POST_BUILD
1198                 COMMAND "${CMAKE_COMMAND}"
1199                     -DINPUT_FILE=liblzma.def.in
1200                     -DOUTPUT_FILE=liblzma.def
1201                     -P
1202                     "${CMAKE_CURRENT_SOURCE_DIR}/cmake/remove-ordinals.cmake"
1203                 BYPRODUCTS "liblzma.def"
1204                 VERBATIM)
1205         endif()
1206     else()
1207         # Disable __declspec(dllimport) when linking against static liblzma.
1208         target_compile_definitions(liblzma INTERFACE LZMA_API_STATIC)
1209     endif()
1210 elseif(BUILD_SHARED_LIBS AND CMAKE_SYSTEM_NAME STREQUAL "Linux" AND
1211        NOT CMAKE_SYSTEM_PROCESSOR MATCHES "[Mm]icro[Bb]laze")
1212     # GNU/Linux-specific symbol versioning for shared liblzma.
1213     # This includes a few extra compatibility symbols for RHEL/CentOS 7
1214     # which are pointless on non-glibc non-Linux systems.
1215     #
1216     # As a special case, GNU/Linux on MicroBlaze gets the generic
1217     # symbol versioning because GCC 12 doesn't support the __symver__
1218     # attribute on MicroBlaze. On Linux, CMAKE_SYSTEM_PROCESSOR comes
1219     # from "uname -m" for native builds (should be "microblaze") or from
1220     # the CMake toolchain file (not perfectly standardized but it very
1221     # likely has "microblaze" in lower case or mixed case somewhere in
1222     # the string).
1223     #
1224     # FIXME? Avoid symvers on Linux with non-glibc like musl?
1225     #
1226     # Note that adding link options doesn't affect static builds
1227     # but HAVE_SYMBOL_VERSIONS_LINUX must not be used with static builds
1228     # because it would put symbol versions into the static library which
1229     # can cause problems. It's clearer if all symver related things are
1230     # omitted when not building a shared library.
1231     #
1232     # NOTE: Set it explicitly to 1 to make it clear that versioning is
1233     # done unconditionally in the C files.
1234     target_compile_definitions(liblzma PRIVATE HAVE_SYMBOL_VERSIONS_LINUX=1)
1235     target_link_options(liblzma PRIVATE
1236         "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_linux.map"
1237     )
1238     set_target_properties(liblzma PROPERTIES
1239         LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_linux.map"
1240     )
1241 elseif(BUILD_SHARED_LIBS AND (CMAKE_SYSTEM_NAME STREQUAL "FreeBSD" OR
1242                               CMAKE_SYSTEM_NAME STREQUAL "Linux"))
1243     # Generic symbol versioning for shared liblzma is used on FreeBSD and
1244     # also on GNU/Linux on MicroBlaze.
1245     target_link_options(liblzma PRIVATE
1246         "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_generic.map"
1247     )
1248     set_target_properties(liblzma PROPERTIES
1249         LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_generic.map"
1250     )
1251 endif()
1253 set_target_properties(liblzma PROPERTIES
1254     # At least for now the package versioning matches the rules used for
1255     # shared library versioning (excluding development releases) so it is
1256     # fine to use the package version here.
1257     SOVERSION "${xz_VERSION_MAJOR}"
1258     VERSION "${xz_VERSION}"
1260     # It's liblzma.so or liblzma.dll, not libliblzma.so or lzma.dll.
1261     # Avoid the name lzma.dll because it would conflict with LZMA SDK.
1262     PREFIX ""
1263     IMPORT_PREFIX ""
1266 # Create liblzma-config-version.cmake.
1268 # FIXME: SameMajorVersion is correct for stable releases but it is wrong
1269 # for development releases where each release may have incompatible changes.
1270 include(CMakePackageConfigHelpers)
1271 write_basic_package_version_file(
1272     "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config-version.cmake"
1273     VERSION "${liblzma_VERSION}"
1274     COMPATIBILITY SameMajorVersion)
1276 # Create liblzma-config.cmake. We use this spelling instead of
1277 # liblzmaConfig.cmake to make find_package work in case insensitive
1278 # manner even with case sensitive file systems. This gives more consistent
1279 # behavior between operating systems. This optionally includes a dependency
1280 # on a threading library, so the contents are created in two separate parts.
1281 # The "second half" is always needed, so create it first.
1282 set(LZMA_CONFIG_CONTENTS
1283 "include(\"\${CMAKE_CURRENT_LIST_DIR}/liblzma-targets.cmake\")
1285 if(NOT TARGET LibLZMA::LibLZMA)
1286     # Be compatible with the spelling used by the FindLibLZMA module. This
1287     # doesn't use ALIAS because it would make CMake resolve LibLZMA::LibLZMA
1288     # to liblzma::liblzma instead of keeping the original spelling. Keeping
1289     # the original spelling is important for good FindLibLZMA compatibility.
1290     add_library(LibLZMA::LibLZMA INTERFACE IMPORTED)
1291     set_target_properties(LibLZMA::LibLZMA PROPERTIES
1292                           INTERFACE_LINK_LIBRARIES liblzma::liblzma)
1293 endif()
1296 if(USE_POSIX_THREADS)
1297     set(LZMA_CONFIG_CONTENTS
1298 "include(CMakeFindDependencyMacro)
1299 set(THREADS_PREFER_PTHREAD_FLAG TRUE)
1300 find_dependency(Threads)
1302 ${LZMA_CONFIG_CONTENTS}
1304 endif()
1306 file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config.cmake"
1307         "${LZMA_CONFIG_CONTENTS}")
1309 # Set CMAKE_INSTALL_LIBDIR and friends.
1310 include(GNUInstallDirs)
1312 # Create liblzma.pc.
1313 set(prefix "${CMAKE_INSTALL_PREFIX}")
1314 set(exec_prefix "${CMAKE_INSTALL_PREFIX}")
1315 set(libdir "${CMAKE_INSTALL_FULL_LIBDIR}")
1316 set(includedir "${CMAKE_INSTALL_FULL_INCLUDEDIR}")
1317 set(PTHREAD_CFLAGS "${CMAKE_THREAD_LIBS_INIT}")
1318 configure_file(src/liblzma/liblzma.pc.in liblzma.pc
1319                @ONLY
1320                NEWLINE_STYLE LF)
1322 # Install the library binary. The INCLUDES specifies the include path that
1323 # is exported for other projects to use but it doesn't install any files.
1324 install(TARGETS liblzma EXPORT liblzmaTargets
1325         RUNTIME  DESTINATION "${CMAKE_INSTALL_BINDIR}"
1326                  COMPONENT liblzma_Runtime
1327         LIBRARY  DESTINATION "${CMAKE_INSTALL_LIBDIR}"
1328                  COMPONENT liblzma_Runtime
1329                  NAMELINK_COMPONENT liblzma_Development
1330         ARCHIVE  DESTINATION "${CMAKE_INSTALL_LIBDIR}"
1331                  COMPONENT liblzma_Development
1332         INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
1334 # Install the liblzma API headers. These use a subdirectory so
1335 # this has to be done as a separate step.
1336 install(DIRECTORY src/liblzma/api/
1337         COMPONENT liblzma_Development
1338         DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
1339         FILES_MATCHING PATTERN "*.h")
1341 # Install the CMake files that other packages can use to find liblzma.
1342 set(liblzma_INSTALL_CMAKEDIR
1343     "${CMAKE_INSTALL_LIBDIR}/cmake/liblzma"
1344     CACHE STRING "Path to liblzma's .cmake files")
1346 install(EXPORT liblzmaTargets
1347         NAMESPACE liblzma::
1348         FILE liblzma-targets.cmake
1349         DESTINATION "${liblzma_INSTALL_CMAKEDIR}"
1350         COMPONENT liblzma_Development)
1352 install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config.cmake"
1353               "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config-version.cmake"
1354         DESTINATION "${liblzma_INSTALL_CMAKEDIR}"
1355         COMPONENT liblzma_Development)
1357 if(NOT MSVC)
1358     install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblzma.pc"
1359             DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig"
1360             COMPONENT liblzma_Development)
1361 endif()
1364 #############################################################################
1365 # Helper functions for installing files
1366 #############################################################################
1368 # For each non-empty element in the list LINK_NAMES, creates symbolic links
1369 # ${LINK_NAME}${LINK_SUFFIX} -> ${TARGET_NAME} in the directory ${DIR}.
1370 # The target file should exist because on Cygwin and MSYS2 symlink creation
1371 # can fail under certain conditions if the target doesn't exist.
1372 function(my_install_symlinks COMPONENT DIR TARGET_NAME LINK_SUFFIX LINK_NAMES)
1373     install(CODE "set(D \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/${DIR}\")
1374                  foreach(L ${LINK_NAMES})
1375                      file(CREATE_LINK \"${TARGET_NAME}\"
1376                                       \"\${D}/\${L}${LINK_SUFFIX}\"
1377                                       SYMBOLIC)
1378                  endforeach()"
1379             COMPONENT "${COMPONENT}")
1380 endfunction()
1382 # Installs a man page file of a given language ("" for the untranslated file)
1383 # and optionally its alternative names as symlinks. This is a helper function
1384 # for my_install_man() below.
1385 function(my_install_man_lang COMPONENT SRC_FILE MAN_LANG LINK_NAMES)
1386     # Get the man page section from the filename suffix.
1387     string(REGEX REPLACE "^.*\.([^/.]+)$" "\\1" MAN_SECTION "${SRC_FILE}")
1389     # A few man pages might be missing from translations.
1390     # Don't attempt to install them or create the related symlinks.
1391     if(NOT MAN_LANG STREQUAL "" AND NOT EXISTS "${SRC_FILE}")
1392         return()
1393     endif()
1395     # Installing the file must be done before creating the symlinks
1396     # due to Cygwin and MSYS2.
1397     install(FILES "${SRC_FILE}"
1398             DESTINATION "${CMAKE_INSTALL_MANDIR}/${MAN_LANG}/man${MAN_SECTION}"
1399             COMPONENT "${COMPONENT}")
1401     # Get the basename of the file to be used as the symlink target.
1402     get_filename_component(BASENAME "${SRC_FILE}" NAME)
1404     # LINK_NAMES don't contain the man page filename suffix (like ".1")
1405     # so it needs to be told to my_install_symlinks.
1406     my_install_symlinks("${COMPONENT}"
1407                         "${CMAKE_INSTALL_MANDIR}/${MAN_LANG}/man${MAN_SECTION}"
1408                         "${BASENAME}" ".${MAN_SECTION}" "${LINK_NAMES}")
1409 endfunction()
1411 # Installs a man page file and optionally its alternative names as symlinks.
1412 # Does the same for translations if ENABLE_NLS.
1413 function(my_install_man COMPONENT SRC_FILE LINK_NAMES)
1414     my_install_man_lang("${COMPONENT}" "${SRC_FILE}" "" "${LINK_NAMES}")
1416     if(ENABLE_NLS)
1417         # Find the translated versions of this man page.
1418         get_filename_component(BASENAME "${SRC_FILE}" NAME)
1419         file(GLOB MAN_FILES "po4a/man/*/${BASENAME}")
1421         foreach(F ${MAN_FILES})
1422             get_filename_component(MAN_LANG "${F}" DIRECTORY)
1423             get_filename_component(MAN_LANG "${MAN_LANG}" NAME)
1424             my_install_man_lang("${COMPONENT}" "${F}" "${MAN_LANG}"
1425                                 "${LINK_NAMES}")
1426         endforeach()
1427     endif()
1428 endfunction()
1431 #############################################################################
1432 # libgnu (getopt_long)
1433 #############################################################################
1435 # This mirrors how the Autotools build system handles the getopt_long
1436 # replacement, calling the object library libgnu since the replacement
1437 # version comes from Gnulib.
1438 add_library(libgnu OBJECT)
1440 # CMake requires that even an object library must have at least once source
1441 # file. So we give it a header file that results in no output files.
1443 # NOTE: Using a file outside the lib directory makes it possible to
1444 # delete lib/*.h and lib/*.c and still keep the build working if
1445 # getopt_long replacement isn't needed. It's convenient if one wishes
1446 # to be certain that no GNU LGPL code gets included in the binaries.
1447 target_sources(libgnu PRIVATE src/common/sysdefs.h)
1449 # The Ninja Generator requires setting the linker language since it cannot
1450 # guess the programming language of just a header file. Setting this
1451 # property avoids needing an empty .c file or an non-empty unnecessary .c
1452 # file.
1453 set_target_properties(libgnu PROPERTIES LINKER_LANGUAGE C)
1455 # Create /lib directory in the build directory and add it to the include path.
1456 file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/lib")
1457 target_include_directories(libgnu PUBLIC "${CMAKE_CURRENT_BINARY_DIR}/lib")
1459 # Include /lib from the source directory. It does no harm even if none of
1460 # the Gnulib replacements are used.
1461 target_include_directories(libgnu PUBLIC lib)
1463 # The command line tools need getopt_long in order to parse arguments. If
1464 # the system does not have a getopt_long implementation we can use the one
1465 # from Gnulib instead.
1466 check_symbol_exists(getopt_long getopt.h HAVE_GETOPT_LONG)
1468 if(NOT HAVE_GETOPT_LONG)
1469     # Set the __GETOPT_PREFIX definition to "rpl_" (replacement) to avoid
1470     # name conflicts with libc symbols. The same prefix is set if using
1471     # the Autotools build (m4/getopt.m4).
1472     target_compile_definitions(libgnu PUBLIC "__GETOPT_PREFIX=rpl_")
1474     # Create a custom copy command to copy the getopt header to the build
1475     # directory and re-copy it if it is updated. (Gnulib does it this way
1476     # because it allows choosing which .in.h files to actually use in the
1477     # build. We need just getopt.h so this is a bit overcomplicated for
1478     # a single header file only.)
1479     add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1480         COMMAND "${CMAKE_COMMAND}" -E copy
1481             "${CMAKE_CURRENT_SOURCE_DIR}/lib/getopt.in.h"
1482             "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1483         MAIN_DEPENDENCY "${CMAKE_CURRENT_SOURCE_DIR}/lib/getopt.in.h"
1484         VERBATIM)
1486     target_sources(libgnu PRIVATE
1487         lib/getopt1.c
1488         lib/getopt.c
1489         lib/getopt_int.h
1490         lib/getopt-cdefs.h
1491         lib/getopt-core.h
1492         lib/getopt-ext.h
1493         lib/getopt-pfx-core.h
1494         lib/getopt-pfx-ext.h
1495         "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1496     )
1497 endif()
1500 #############################################################################
1501 # xzdec and lzmadec
1502 #############################################################################
1504 if(HAVE_DECODERS AND (NOT MSVC OR MSVC_VERSION GREATER_EQUAL 1900))
1505     foreach(XZDEC xzdec lzmadec)
1506         add_executable("${XZDEC}"
1507             src/common/sysdefs.h
1508             src/common/tuklib_common.h
1509             src/common/tuklib_config.h
1510             src/common/tuklib_exit.c
1511             src/common/tuklib_exit.h
1512             src/common/tuklib_gettext.h
1513             src/common/tuklib_progname.c
1514             src/common/tuklib_progname.h
1515             src/xzdec/xzdec.c
1516         )
1518         target_include_directories("${XZDEC}" PRIVATE
1519             src/common
1520             src/liblzma/api
1521         )
1523         target_link_libraries("${XZDEC}" PRIVATE liblzma libgnu)
1525         if(WIN32)
1526             # Add the Windows resource file for xzdec.exe or lzmadec.exe.
1527             target_sources("${XZDEC}" PRIVATE src/xzdec/xzdec_w32res.rc)
1528             set_target_properties("${XZDEC}" PROPERTIES
1529                 LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1530             )
1531         endif()
1533         if(SANDBOX_COMPILE_DEFINITION)
1534             target_compile_definitions("${XZDEC}" PRIVATE
1535                                     "${SANDBOX_COMPILE_DEFINITION}")
1536         endif()
1538         tuklib_progname("${XZDEC}")
1540         install(TARGETS "${XZDEC}"
1541                 RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1542                         COMPONENT "${XZDEC}_Runtime")
1543     endforeach()
1545     # This is the only build-time difference with lzmadec.
1546     target_compile_definitions(lzmadec PRIVATE "LZMADEC")
1548     if(UNIX)
1549         # NOTE: This puts the lzmadec.1 symlinks into xzdec_Documentation.
1550         # This isn't great but doing them separately with translated
1551         # man pages would require extra code. So this has to suffice for now.
1552         my_install_man(xzdec_Documentation src/xzdec/xzdec.1 lzmadec)
1553     endif()
1554 endif()
1557 #############################################################################
1558 # lzmainfo
1559 #############################################################################
1561 if(HAVE_DECODERS AND (NOT MSVC OR MSVC_VERSION GREATER_EQUAL 1900))
1562     add_executable(lzmainfo
1563         src/common/sysdefs.h
1564         src/common/tuklib_common.h
1565         src/common/tuklib_config.h
1566         src/common/tuklib_exit.c
1567         src/common/tuklib_exit.h
1568         src/common/tuklib_gettext.h
1569         src/common/tuklib_progname.c
1570         src/common/tuklib_progname.h
1571         src/lzmainfo/lzmainfo.c
1572     )
1574     target_include_directories(lzmainfo PRIVATE
1575         src/common
1576         src/liblzma/api
1577     )
1579     target_link_libraries(lzmainfo PRIVATE liblzma libgnu)
1581     if(WIN32)
1582         # Add the Windows resource file for lzmainfo.exe.
1583         target_sources(lzmainfo PRIVATE src/lzmainfo/lzmainfo_w32res.rc)
1584         set_target_properties(lzmainfo PROPERTIES
1585             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1586         )
1587     endif()
1589     tuklib_progname(lzmainfo)
1591     # NOTE: The translations are in the "xz" domain and the .mo files are
1592     # installed as part of the "xz" target.
1593     if(ENABLE_NLS)
1594         target_link_libraries(lzmainfo PRIVATE Intl::Intl)
1596         target_compile_definitions(lzmainfo PRIVATE
1597                 ENABLE_NLS
1598                 PACKAGE="${TRANSLATION_DOMAIN}"
1599                 LOCALEDIR="${CMAKE_INSTALL_FULL_LOCALEDIR}"
1600         )
1601     endif()
1603     install(TARGETS lzmainfo
1604             RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1605                     COMPONENT lzmainfo_Runtime)
1607     if(UNIX)
1608         my_install_man(lzmainfo_Documentation src/lzmainfo/lzmainfo.1 "")
1609     endif()
1610 endif()
1613 #############################################################################
1614 # xz
1615 #############################################################################
1617 if(NOT MSVC OR MSVC_VERSION GREATER_EQUAL 1900)
1618     add_executable(xz
1619         src/common/mythread.h
1620         src/common/sysdefs.h
1621         src/common/tuklib_common.h
1622         src/common/tuklib_config.h
1623         src/common/tuklib_exit.c
1624         src/common/tuklib_exit.h
1625         src/common/tuklib_gettext.h
1626         src/common/tuklib_integer.h
1627         src/common/tuklib_mbstr.h
1628         src/common/tuklib_mbstr_fw.c
1629         src/common/tuklib_mbstr_width.c
1630         src/common/tuklib_open_stdxxx.c
1631         src/common/tuklib_open_stdxxx.h
1632         src/common/tuklib_progname.c
1633         src/common/tuklib_progname.h
1634         src/xz/args.c
1635         src/xz/args.h
1636         src/xz/coder.c
1637         src/xz/coder.h
1638         src/xz/file_io.c
1639         src/xz/file_io.h
1640         src/xz/hardware.c
1641         src/xz/hardware.h
1642         src/xz/main.c
1643         src/xz/main.h
1644         src/xz/message.c
1645         src/xz/message.h
1646         src/xz/mytime.c
1647         src/xz/mytime.h
1648         src/xz/options.c
1649         src/xz/options.h
1650         src/xz/private.h
1651         src/xz/sandbox.c
1652         src/xz/sandbox.h
1653         src/xz/signals.c
1654         src/xz/signals.h
1655         src/xz/suffix.c
1656         src/xz/suffix.h
1657         src/xz/util.c
1658         src/xz/util.h
1659     )
1661     target_include_directories(xz PRIVATE
1662         src/common
1663         src/liblzma/api
1664     )
1666     if(HAVE_DECODERS)
1667         target_sources(xz PRIVATE
1668             src/xz/list.c
1669             src/xz/list.h
1670         )
1671     endif()
1673     target_link_libraries(xz PRIVATE liblzma libgnu)
1675     target_compile_definitions(xz PRIVATE ASSUME_RAM=128)
1677     if(WIN32)
1678         # Add the Windows resource file for xz.exe.
1679         target_sources(xz PRIVATE src/xz/xz_w32res.rc)
1680         set_target_properties(xz PROPERTIES
1681             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1682         )
1683     endif()
1685     if(SANDBOX_COMPILE_DEFINITION)
1686         target_compile_definitions(xz PRIVATE "${SANDBOX_COMPILE_DEFINITION}")
1687     endif()
1689     tuklib_progname(xz)
1690     tuklib_mbstr(xz)
1692     check_symbol_exists(optreset getopt.h HAVE_OPTRESET)
1693     tuklib_add_definition_if(xz HAVE_OPTRESET)
1695     check_symbol_exists(posix_fadvise fcntl.h HAVE_POSIX_FADVISE)
1696     tuklib_add_definition_if(xz HAVE_POSIX_FADVISE)
1698     # How to get file time:
1699     check_struct_has_member("struct stat" st_atim.tv_nsec
1700                             "sys/types.h;sys/stat.h"
1701                             HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1702     if(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1703         tuklib_add_definitions(xz HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1704     else()
1705         check_struct_has_member("struct stat" st_atimespec.tv_nsec
1706                                 "sys/types.h;sys/stat.h"
1707                                 HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1708         if(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1709             tuklib_add_definitions(xz HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1710         else()
1711             check_struct_has_member("struct stat" st_atimensec
1712                                     "sys/types.h;sys/stat.h"
1713                                     HAVE_STRUCT_STAT_ST_ATIMENSEC)
1714             tuklib_add_definition_if(xz HAVE_STRUCT_STAT_ST_ATIMENSEC)
1715         endif()
1716     endif()
1718     # How to set file time:
1719     check_symbol_exists(futimens "sys/types.h;sys/stat.h" HAVE_FUTIMENS)
1720     if(HAVE_FUTIMENS)
1721         tuklib_add_definitions(xz HAVE_FUTIMENS)
1722     else()
1723         check_symbol_exists(futimes "sys/time.h" HAVE_FUTIMES)
1724         if(HAVE_FUTIMES)
1725             tuklib_add_definitions(xz HAVE_FUTIMES)
1726         else()
1727             check_symbol_exists(futimesat "sys/time.h" HAVE_FUTIMESAT)
1728             if(HAVE_FUTIMESAT)
1729                 tuklib_add_definitions(xz HAVE_FUTIMESAT)
1730             else()
1731                 check_symbol_exists(utimes "sys/time.h" HAVE_UTIMES)
1732                 if(HAVE_UTIMES)
1733                     tuklib_add_definitions(xz HAVE_UTIMES)
1734                 else()
1735                     check_symbol_exists(_futime "sys/utime.h" HAVE__FUTIME)
1736                     if(HAVE__FUTIME)
1737                         tuklib_add_definitions(xz HAVE__FUTIME)
1738                     else()
1739                         check_symbol_exists(utime "utime.h" HAVE_UTIME)
1740                         tuklib_add_definition_if(xz HAVE_UTIME)
1741                     endif()
1742                 endif()
1743             endif()
1744         endif()
1745     endif()
1747     if(ENABLE_NLS)
1748         target_link_libraries(xz PRIVATE Intl::Intl)
1750         target_compile_definitions(xz PRIVATE
1751                 ENABLE_NLS
1752                 PACKAGE="${TRANSLATION_DOMAIN}"
1753                 LOCALEDIR="${CMAKE_INSTALL_FULL_LOCALEDIR}"
1754         )
1756         file(STRINGS po/LINGUAS LINGUAS)
1758         # Where to find .gmo files. If msgfmt is available, the .po files
1759         # will be converted as part of the build. Otherwise we will use
1760         # the pre-generated .gmo files which are included in XZ Utils
1761         # tarballs by Autotools.
1762         set(GMO_DIR "${CMAKE_CURRENT_SOURCE_DIR}/po")
1764         if(GETTEXT_FOUND)
1765             # NOTE: gettext_process_po_files' INSTALL_DESTINATION is
1766             # incompatible with how Autotools requires the .po files to
1767             # be named. CMake would require each .po file to be named with
1768             # the translation domain and thus each .po file would need its
1769             # own language-specific directory (like "po/fi/xz.po"). On top
1770             # of this, INSTALL_DESTINATION doesn't allow specifying COMPONENT
1771             # and thus the .mo files go into "Unspecified" component. So we
1772             # can use gettext_process_po_files to convert the .po files but
1773             # installation needs to be done with our own code.
1774             #
1775             # Also, the .gmo files will go to root of the build directory
1776             # instead of neatly into a subdirectory. This is hardcoded in
1777             # CMake's FindGettext.cmake.
1778             foreach(LANG IN LISTS LINGUAS)
1779                 gettext_process_po_files("${LANG}" ALL
1780                         PO_FILES "${CMAKE_CURRENT_SOURCE_DIR}/po/${LANG}.po")
1781             endforeach()
1783             set(GMO_DIR "${CMAKE_CURRENT_BINARY_DIR}")
1784         endif()
1786         foreach(LANG IN LISTS LINGUAS)
1787             install(
1788                 FILES "${GMO_DIR}/${LANG}.gmo"
1789                 DESTINATION "${CMAKE_INSTALL_LOCALEDIR}/${LANG}/LC_MESSAGES"
1790                 RENAME "${TRANSLATION_DOMAIN}.mo"
1791                 COMPONENT xz_Runtime)
1792         endforeach()
1793     endif()
1795     # This command must be before the symlink creation to keep things working
1796     # on Cygwin and MSYS2 in all cases.
1797     #
1798     #   - Cygwin can encode symlinks in multiple ways. This can be
1799     #     controlled via the environment variable "CYGWIN". If it contains
1800     #     "winsymlinks:nativestrict" then symlink creation will fail if
1801     #     the link target doesn't exist. This mode isn't the default though.
1802     #     See: https://cygwin.com/faq.html#faq.api.symlinks
1803     #
1804     #   - MSYS2 supports the same winsymlinks option in the environment
1805     #     variable "MSYS" (not "MSYS2). The default in MSYS2 is to make
1806     #     a copy of the file instead of any kind of symlink. Thus the link
1807     #     target must exist or the creation of the "symlink" (copy) will fail.
1808     #
1809     # Our installation order must be such that when a symbolic link is created
1810     # its target must already exists. There is no race condition for parallel
1811     # builds because the generated cmake_install.cmake executes serially.
1812     install(TARGETS xz
1813             RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1814                     COMPONENT xz_Runtime)
1816     if(UNIX)
1817         option(CREATE_XZ_SYMLINKS "Create unxz and xzcat symlinks" ON)
1818         option(CREATE_LZMA_SYMLINKS "Create lzma, unlzma, and lzcat symlinks"
1819                ON)
1820         set(XZ_LINKS)
1822         if(CREATE_XZ_SYMLINKS)
1823             list(APPEND XZ_LINKS "unxz" "xzcat")
1824         endif()
1826         if(CREATE_LZMA_SYMLINKS)
1827             list(APPEND XZ_LINKS "lzma" "unlzma" "lzcat")
1828         endif()
1830         # On Cygwin, don't add the .exe suffix to the symlinks.
1831         #
1832         # FIXME? Does this make sense on MSYS & MSYS2 where "ln -s"
1833         # by default makes copies? Inside MSYS & MSYS2 it is possible
1834         # to execute files without the .exe suffix but not outside
1835         # (like in Command Prompt). Omitting the suffix matches
1836         # what configure.ac has done for many years though.
1837         my_install_symlinks(xz_Runtime "${CMAKE_INSTALL_BINDIR}"
1838                             "xz${CMAKE_EXECUTABLE_SUFFIX}" "" "${XZ_LINKS}")
1840         # Install the man pages and (optionally) their symlinks
1841         # and translations.
1842         my_install_man(xz_Documentation src/xz/xz.1 "${XZ_LINKS}")
1843     endif()
1844 endif()
1847 #############################################################################
1848 # Scripts
1849 #############################################################################
1851 if(UNIX)
1852     # NOTE: This isn't as sophisticated as in the Autotools build which
1853     # uses posix-shell.m4 but hopefully this doesn't need to be either.
1854     # CMake likely won't be used on as many (old) obscure systems as the
1855     # Autotools-based builds are.
1856     if(CMAKE_SYSTEM_NAME STREQUAL "SunOS" AND EXISTS "/usr/xpg4/bin/sh")
1857         set(POSIX_SHELL_DEFAULT "/usr/xpg4/bin/sh")
1858     else()
1859         set(POSIX_SHELL_DEFAULT "/bin/sh")
1860     endif()
1862     set(POSIX_SHELL "${POSIX_SHELL_DEFAULT}" CACHE STRING
1863         "Shell to use for scripts (xzgrep and others)")
1865     # Guess the extra path to add from POSIX_SHELL. Autotools-based build
1866     # has a separate option --enable-path-for-scripts=PREFIX but this is
1867     # enough for Solaris.
1868     set(enable_path_for_scripts)
1869     get_filename_component(POSIX_SHELL_DIR "${POSIX_SHELL}" DIRECTORY)
1871     if(NOT POSIX_SHELL_DIR STREQUAL "/bin" AND
1872             NOT POSIX_SHELL_DIR STREQUAL "/usr/bin")
1873         set(enable_path_for_scripts "PATH=${POSIX_SHELL_DIR}:\$PATH")
1874     endif()
1876     set(XZDIFF_LINKS xzcmp)
1877     set(XZGREP_LINKS xzegrep xzfgrep)
1878     set(XZMORE_LINKS)
1879     set(XZLESS_LINKS)
1881     if(CREATE_LZMA_SYMLINKS)
1882         list(APPEND XZDIFF_LINKS lzdiff lzcmp)
1883         list(APPEND XZGREP_LINKS lzgrep lzegrep lzfgrep)
1884         list(APPEND XZMORE_LINKS lzmore)
1885         list(APPEND XZLESS_LINKS lzless)
1886     endif()
1888     set(xz "xz")
1890     foreach(S xzdiff xzgrep xzmore xzless)
1891         configure_file("src/scripts/${S}.in" "${S}"
1892                @ONLY
1893                NEWLINE_STYLE LF)
1895         install(PROGRAMS "${CMAKE_CURRENT_BINARY_DIR}/${S}"
1896                 DESTINATION "${CMAKE_INSTALL_BINDIR}"
1897                 COMPONENT scripts_Runtime)
1898     endforeach()
1900     # file(CHMOD ...) would need CMake 3.19 so use execute_process instead.
1901     # Using +x is fine even if umask was 077. If execute bit is set at all
1902     # then "make install" will set it for group and other access bits too.
1903     execute_process(COMMAND chmod +x xzdiff xzgrep xzmore xzless
1904                     WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}")
1906     unset(xz)
1907     unset(POSIX_SHELL)
1908     unset(enable_path_for_scripts)
1910     my_install_symlinks(scripts_Runtime "${CMAKE_INSTALL_BINDIR}" xzdiff ""
1911                         "${XZDIFF_LINKS}")
1913     my_install_symlinks(scripts_Runtime "${CMAKE_INSTALL_BINDIR}" xzgrep ""
1914                         "${XZGREP_LINKS}")
1916     my_install_symlinks(scripts_Runtime "${CMAKE_INSTALL_BINDIR}" xzmore ""
1917                         "${XZMORE_LINKS}")
1919     my_install_symlinks(scripts_Runtime "${CMAKE_INSTALL_BINDIR}" xzless ""
1920                         "${XZLESS_LINKS}")
1922     my_install_man(scripts_Documentation src/scripts/xzdiff.1 "${XZDIFF_LINKS}")
1923     my_install_man(scripts_Documentation src/scripts/xzgrep.1 "${XZGREP_LINKS}")
1924     my_install_man(scripts_Documentation src/scripts/xzmore.1 "${XZMORE_LINKS}")
1925     my_install_man(scripts_Documentation src/scripts/xzless.1 "${XZLESS_LINKS}")
1926 endif()
1929 #############################################################################
1930 # Documentation
1931 #############################################################################
1933 # Use OPTIONAL because doc/api might not exist. The liblzma API docs
1934 # can be generated by running "doxygen/update-doxygen".
1935 install(DIRECTORY doc/api doc/examples
1936         DESTINATION "${CMAKE_INSTALL_DOCDIR}"
1937         COMPONENT liblzma_Documentation
1938         OPTIONAL)
1940 # GPLv2 applies to the scripts. If GNU getopt_long is used then
1941 # LGPLv2.1 applies to the command line tools but, using the
1942 # section 3 of LGPLv2.1, GNU getopt_long can be handled as GPLv2 too.
1943 # Thus GPLv2 should be enough here.
1944 install(FILES AUTHORS
1945               COPYING
1946               COPYING.0BSD
1947               COPYING.GPLv2
1948               NEWS
1949               README
1950               THANKS
1951               doc/faq.txt
1952               doc/history.txt
1953               doc/lzma-file-format.txt
1954               doc/xz-file-format.txt
1955         DESTINATION "${CMAKE_INSTALL_DOCDIR}"
1956         COMPONENT Documentation)
1959 #############################################################################
1960 # Tests
1961 #############################################################################
1963 include(CTest)
1965 if(BUILD_TESTING)
1966     set(LIBLZMA_TESTS
1967         test_bcj_exact_size
1968         test_block_header
1969         test_check
1970         test_filter_flags
1971         test_filter_str
1972         test_hardware
1973         test_index
1974         test_index_hash
1975         test_lzip_decoder
1976         test_memlimit
1977         test_stream_flags
1978         test_vli
1979     )
1981     foreach(TEST IN LISTS LIBLZMA_TESTS)
1982         add_executable("${TEST}" "tests/${TEST}.c")
1984         target_include_directories("${TEST}" PRIVATE
1985             src/common
1986             src/liblzma/api
1987             src/liblzma
1988         )
1990         target_link_libraries("${TEST}" PRIVATE liblzma)
1992         # Put the test programs into their own subdirectory so they don't
1993         # pollute the top-level dir which might contain xz and xzdec.
1994         set_target_properties("${TEST}" PROPERTIES
1995             RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/tests_bin"
1996         )
1998         add_test(NAME "${TEST}"
1999                  COMMAND "${CMAKE_CURRENT_BINARY_DIR}/tests_bin/${TEST}"
2000         )
2002         # Set srcdir environment variable so that the tests find their
2003         # input files from the source tree.
2004         #
2005         # Set the return code for skipped tests to match Automake convention.
2006         set_tests_properties("${TEST}" PROPERTIES
2007             ENVIRONMENT "srcdir=${CMAKE_CURRENT_SOURCE_DIR}/tests"
2008             SKIP_RETURN_CODE 77
2009         )
2010     endforeach()
2012     if(UNIX AND HAVE_DECODERS)
2013         file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_scripts")
2015         add_test(NAME test_scripts.sh
2016             COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_scripts.sh" ".."
2017             WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_scripts"
2018         )
2020         set_tests_properties(test_scripts.sh PROPERTIES
2021             ENVIRONMENT "srcdir=${CMAKE_CURRENT_SOURCE_DIR}/tests"
2022             SKIP_RETURN_CODE 77
2023         )
2024     endif()
2025 endif()