xzdec: Add sandbox support for Pledge, Capsicum, and Landlock.
[xz.git] / CMakeLists.txt
blob1e9af0e5e6f9cb4727c513691ed34d4352664e6f
1 #############################################################################
3 # Very limited CMake support for building some parts of XZ Utils
5 # For now, this is intended to be useful to build static or shared liblzma
6 # on Windows with MSVC (to avoid the need to maintain Visual Studio project
7 # files). Building liblzma on a few other platforms should work too but it
8 # is somewhat experimental and not as portable as using ./configure.
10 # On some platforms this builds also xz and xzdec, but these are
11 # highly experimental and meant for testing only:
12 #   - No translations
14 # Other missing things:
15 #   - No xzgrep or other scripts or their symlinks
16 #   - No xz tests (liblzma tests only)
18 # NOTE: Even if the code compiles without warnings, the end result may be
19 # different than via ./configure. Specifically, the list of #defines
20 # may be different (if so, probably this CMakeLists.txt got them wrong).
22 # This file provides the following installation components (if you only
23 # need liblzma, install only its components!):
24 #   - liblzma_Runtime
25 #   - liblzma_Development
26 #   - xz (on some platforms only)
27 #   - xzdec (on some platforms only)
29 # To find the target liblzma::liblzma from other packages, use the CONFIG
30 # option with find_package() to avoid a conflict with the FindLibLZMA module
31 # with case-insensitive file systems. For example, to require liblzma 5.2.5
32 # or a newer compatible version:
34 #     find_package(liblzma 5.2.5 REQUIRED CONFIG)
35 #     target_link_libraries(my_application liblzma::liblzma)
37 #############################################################################
39 # Author: Lasse Collin
41 # This file has been put into the public domain.
42 # You can do whatever you want with this file.
44 #############################################################################
46 cmake_minimum_required(VERSION 3.13...3.27 FATAL_ERROR)
48 include(CMakePushCheckState)
49 include(CheckIncludeFile)
50 include(CheckSymbolExists)
51 include(CheckStructHasMember)
52 include(CheckCSourceCompiles)
53 include(cmake/tuklib_large_file_support.cmake)
54 include(cmake/tuklib_integer.cmake)
55 include(cmake/tuklib_cpucores.cmake)
56 include(cmake/tuklib_physmem.cmake)
57 include(cmake/tuklib_progname.cmake)
58 include(cmake/tuklib_mbstr.cmake)
60 set(PACKAGE_NAME "XZ Utils")
61 set(PACKAGE_BUGREPORT "xz@tukaani.org")
62 set(PACKAGE_URL "https://tukaani.org/xz/")
64 # Get the package version from version.h into PACKAGE_VERSION variable.
65 file(READ src/liblzma/api/lzma/version.h PACKAGE_VERSION)
66 string(REGEX REPLACE
67 "^.*\n\
68 #define LZMA_VERSION_MAJOR ([0-9]+)\n\
69 .*\
70 #define LZMA_VERSION_MINOR ([0-9]+)\n\
71 .*\
72 #define LZMA_VERSION_PATCH ([0-9]+)\n\
73 .*$"
74        "\\1.\\2.\\3" PACKAGE_VERSION "${PACKAGE_VERSION}")
76 # Among other things, this gives us variables xz_VERSION and xz_VERSION_MAJOR.
77 project(xz VERSION "${PACKAGE_VERSION}" LANGUAGES C)
79 # We need a compiler that supports enough C99 or newer (variable-length arrays
80 # aren't needed, those are optional in C17). Setting CMAKE_C_STANDARD here
81 # makes it the default for all targets. It doesn't affect the INTERFACE so
82 # liblzma::liblzma won't end up with INTERFACE_COMPILE_FEATURES "c_std_99"
83 # (the API headers are C89 and C++ compatible).
84 set(CMAKE_C_STANDARD 99)
85 set(CMAKE_C_STANDARD_REQUIRED ON)
87 # On Apple OSes, don't build executables as bundles:
88 set(CMAKE_MACOSX_BUNDLE OFF)
90 # windres from GNU binutils can be tricky with command line arguments
91 # that contain spaces or other funny characters. Unfortunately we need
92 # a space in PACKAGE_NAME. Using \x20 to encode the US-ASCII space seems
93 # to work in both cmd.exe and /bin/sh.
95 # However, even \x20 isn't enough in all situations, resulting in
96 # "syntax error" from windres. Using --use-temp-file prevents windres
97 # from using popen() and this seems to fix the problem.
99 # llvm-windres from Clang/LLVM 16.0.6 and older: The \x20 results
100 # in "XZx20Utils" in the compiled binary. The option --use-temp-file
101 # makes no difference.
103 # llvm-windres 17.0.0 and later: It emulates GNU windres more accurately, so
104 # the workarounds used with GNU windres must be used with llvm-windres too.
106 # CMake 3.27 doesn't have CMAKE_RC_COMPILER_ID so we rely on
107 # CMAKE_C_COMPILER_ID.
108 if((MINGW OR CYGWIN OR MSYS) AND (
109         NOT CMAKE_C_COMPILER_ID STREQUAL "Clang" OR
110         CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL "17"))
111     # Use workarounds with GNU windres and llvm-windres >= 17.0.0. The \x20
112     # in PACKAGE_NAME_DEFINITION works with gcc and clang too so we don't need
113     # to worry how to pass different flags to windres and the C compiler.
114     # Keep the original PACKAGE_NAME intact for generation of liblzma.pc.
115     string(APPEND CMAKE_RC_FLAGS " --use-temp-file")
116     string(REPLACE " " "\\x20" PACKAGE_NAME_DEFINITION "${PACKAGE_NAME}")
117 else()
118     # Elsewhere a space is safe. This also keeps things compatible with
119     # EBCDIC in case CMake-based build is ever done on such a system.
120     set(PACKAGE_NAME_DEFINITION "${PACKAGE_NAME}")
121 endif()
123 # Definitions common to all targets:
124 add_compile_definitions(
125     # Package info:
126     PACKAGE_NAME="${PACKAGE_NAME_DEFINITION}"
127     PACKAGE_BUGREPORT="${PACKAGE_BUGREPORT}"
128     PACKAGE_URL="${PACKAGE_URL}"
130     # Standard headers and types are available:
131     HAVE_STDBOOL_H
132     HAVE__BOOL
133     HAVE_STDINT_H
134     HAVE_INTTYPES_H
136     # Always enable CRC32 since liblzma should never build without it.
137     HAVE_CHECK_CRC32
139     # Disable assert() checks when no build type has been specified. Non-empty
140     # build types like "Release" and "Debug" handle this by default.
141     $<$<CONFIG:>:NDEBUG>
145 ######################
146 # System definitions #
147 ######################
149 # _GNU_SOURCE and such definitions. This specific macro is special since
150 # it also adds the definitions to CMAKE_REQUIRED_DEFINITIONS.
151 tuklib_use_system_extensions(ALL)
153 # Check for large file support. It's required on some 32-bit platforms and
154 # even on 64-bit MinGW-w64 to get 64-bit off_t. This can be forced off on
155 # the CMake command line if needed: -DLARGE_FILE_SUPPORT=OFF
156 tuklib_large_file_support(ALL)
158 # This is needed by liblzma and xz.
159 tuklib_integer(ALL)
161 # This is used for liblzma.pc generation to add -lrt if needed.
162 set(LIBS)
164 # Check for clock_gettime(). Do this before checking for threading so
165 # that we know there if CLOCK_MONOTONIC is available.
166 check_symbol_exists(clock_gettime time.h HAVE_CLOCK_GETTIME)
168 if(NOT HAVE_CLOCK_GETTIME)
169     # With glibc <= 2.17 or Solaris 10 this needs librt.
170     # Add librt for the next check for HAVE_CLOCK_GETTIME. If it is
171     # found after including the library, we know that librt is required.
172     list(INSERT CMAKE_REQUIRED_LIBRARIES 0 rt)
173     check_symbol_exists(clock_gettime time.h HAVE_CLOCK_GETTIME_LIBRT)
175     # If it was found now, add librt to all targets and keep it in
176     # CMAKE_REQUIRED_LIBRARIES for further tests too.
177     if(HAVE_CLOCK_GETTIME_LIBRT)
178         link_libraries(rt)
179         set(LIBS "-lrt") # For liblzma.pc
180     else()
181         list(REMOVE_AT CMAKE_REQUIRED_LIBRARIES 0)
182     endif()
183 endif()
185 if(HAVE_CLOCK_GETTIME OR HAVE_CLOCK_GETTIME_LIBRT)
186     add_compile_definitions(HAVE_CLOCK_GETTIME)
188     # Check if CLOCK_MONOTONIC is available for clock_gettime().
189     check_symbol_exists(CLOCK_MONOTONIC time.h HAVE_CLOCK_MONOTONIC)
190     tuklib_add_definition_if(ALL HAVE_CLOCK_MONOTONIC)
191 endif()
193 # Options for new enough GCC or Clang on any arch or operating system:
194 if(CMAKE_C_COMPILER_ID MATCHES GNU|Clang)
195     # configure.ac has a long list but it won't be copied here:
196     add_compile_options(-Wall -Wextra)
197 endif()
200 #############################################################################
201 # liblzma
202 #############################################################################
204 option(BUILD_SHARED_LIBS "Build liblzma as a shared library instead of static")
206 add_library(liblzma
207     src/common/mythread.h
208     src/common/sysdefs.h
209     src/common/tuklib_common.h
210     src/common/tuklib_config.h
211     src/common/tuklib_integer.h
212     src/common/tuklib_physmem.c
213     src/common/tuklib_physmem.h
214     src/liblzma/api/lzma.h
215     src/liblzma/api/lzma/base.h
216     src/liblzma/api/lzma/bcj.h
217     src/liblzma/api/lzma/block.h
218     src/liblzma/api/lzma/check.h
219     src/liblzma/api/lzma/container.h
220     src/liblzma/api/lzma/delta.h
221     src/liblzma/api/lzma/filter.h
222     src/liblzma/api/lzma/hardware.h
223     src/liblzma/api/lzma/index.h
224     src/liblzma/api/lzma/index_hash.h
225     src/liblzma/api/lzma/lzma12.h
226     src/liblzma/api/lzma/stream_flags.h
227     src/liblzma/api/lzma/version.h
228     src/liblzma/api/lzma/vli.h
229     src/liblzma/check/check.c
230     src/liblzma/check/check.h
231     src/liblzma/check/crc_common.h
232     src/liblzma/common/block_util.c
233     src/liblzma/common/common.c
234     src/liblzma/common/common.h
235     src/liblzma/common/easy_preset.c
236     src/liblzma/common/easy_preset.h
237     src/liblzma/common/filter_common.c
238     src/liblzma/common/filter_common.h
239     src/liblzma/common/hardware_physmem.c
240     src/liblzma/common/index.c
241     src/liblzma/common/index.h
242     src/liblzma/common/memcmplen.h
243     src/liblzma/common/stream_flags_common.c
244     src/liblzma/common/stream_flags_common.h
245     src/liblzma/common/string_conversion.c
246     src/liblzma/common/vli_size.c
249 target_include_directories(liblzma PRIVATE
250     src/liblzma/api
251     src/liblzma/common
252     src/liblzma/check
253     src/liblzma/lz
254     src/liblzma/rangecoder
255     src/liblzma/lzma
256     src/liblzma/delta
257     src/liblzma/simple
258     src/common
262 ######################
263 # Size optimizations #
264 ######################
266 option(ENABLE_SMALL "Reduce code size at expense of speed. \
267 This may be useful together with CMAKE_BUILD_TYPE=MinSizeRel.")
269 if(ENABLE_SMALL)
270     add_compile_definitions(HAVE_SMALL)
271 endif()
274 ##########
275 # Checks #
276 ##########
278 set(ADDITIONAL_SUPPORTED_CHECKS crc64 sha256)
280 set(ADDITIONAL_CHECK_TYPES "${ADDITIONAL_SUPPORTED_CHECKS}" CACHE STRING
281     "Additional check types to support (crc32 is always built)")
283 foreach(CHECK IN LISTS ADDITIONAL_CHECK_TYPES)
284     if(NOT CHECK IN_LIST ADDITIONAL_SUPPORTED_CHECKS)
285         message(FATAL_ERROR "'${CHECK}' is not a supported check type")
286     endif()
287 endforeach()
289 if(ENABLE_SMALL)
290     target_sources(liblzma PRIVATE src/liblzma/check/crc32_small.c)
291 else()
292     target_sources(liblzma PRIVATE
293         src/liblzma/check/crc32_fast.c
294         src/liblzma/check/crc32_table.c
295         src/liblzma/check/crc32_table_be.h
296         src/liblzma/check/crc32_table_le.h
297     )
298 endif()
300 if("crc64" IN_LIST ADDITIONAL_CHECK_TYPES)
301     add_compile_definitions("HAVE_CHECK_CRC64")
303     if(ENABLE_SMALL)
304         target_sources(liblzma PRIVATE src/liblzma/check/crc64_small.c)
305     else()
306         target_sources(liblzma PRIVATE
307             src/liblzma/check/crc64_fast.c
308             src/liblzma/check/crc64_table.c
309             src/liblzma/check/crc64_table_be.h
310             src/liblzma/check/crc64_table_le.h
311         )
312     endif()
313 endif()
315 if("sha256" IN_LIST ADDITIONAL_CHECK_TYPES)
316     add_compile_definitions("HAVE_CHECK_SHA256")
317     target_sources(liblzma PRIVATE src/liblzma/check/sha256.c)
318 endif()
321 #################
322 # Match finders #
323 #################
325 set(SUPPORTED_MATCH_FINDERS hc3 hc4 bt2 bt3 bt4)
327 set(MATCH_FINDERS "${SUPPORTED_MATCH_FINDERS}" CACHE STRING
328     "Match finders to support (at least one is required for LZMA1 or LZMA2)")
330 foreach(MF IN LISTS MATCH_FINDERS)
331     if(MF IN_LIST SUPPORTED_MATCH_FINDERS)
332         string(TOUPPER "${MF}" MF_UPPER)
333         add_compile_definitions("HAVE_MF_${MF_UPPER}")
334     else()
335         message(FATAL_ERROR "'${MF}' is not a supported match finder")
336     endif()
337 endforeach()
340 #############
341 # Threading #
342 #############
344 # Supported threading methods:
345 # ON    - autodetect the best threading method. The autodetection will
346 #         prefer Windows threading (win95 or vista) over posix if both are
347 #         available. vista threads will be used over win95 unless it is a
348 #         32-bit build.
349 # OFF   - Disable threading.
350 # posix - Use posix threading (pthreads), or throw an error if not available.
351 # win95 - Use Windows win95 threading, or throw an error if not available.
352 # vista - Use Windows vista threading, or throw an error if not available.
353 set(SUPPORTED_THREADING_METHODS ON OFF posix win95 vista)
355 set(ENABLE_THREADS ON CACHE STRING
356     "Threading method: Set to 'ON' to autodetect, 'OFF' to disable threading.")
358 # Create dropdown in CMake GUI since only 1 threading method is possible
359 # to select in a build.
360 set_property(CACHE ENABLE_THREADS
361              PROPERTY STRINGS "${SUPPORTED_THREADING_METHODS}")
363 # This is a flag variable set when win95 threads are used. We must ensure
364 # the combination of enable_small and win95 threads is not used without a
365 # compiler supporting attribute __constructor__.
366 set(USE_WIN95_THREADS OFF)
368 # This is a flag variable set when posix threads (pthreads) are used.
369 # It's needed when creating liblzma-config.cmake where dependency on
370 # Threads::Threads is only needed with pthreads.
371 set(USE_POSIX_THREADS OFF)
373 if(NOT ENABLE_THREADS IN_LIST SUPPORTED_THREADING_METHODS)
374     message(FATAL_ERROR "'${ENABLE_THREADS}' is not a supported "
375                         "threading method")
376 endif()
378 if(ENABLE_THREADS)
379     # Also set THREADS_PREFER_PTHREAD_FLAG since the flag has no effect
380     # for Windows threading.
381     set(THREADS_PREFER_PTHREAD_FLAG TRUE)
382     find_package(Threads REQUIRED)
384     # If both Windows and posix threading are available, prefer Windows.
385     # Note that on Cygwin CMAKE_USE_WIN32_THREADS_INIT is false.
386     if(CMAKE_USE_WIN32_THREADS_INIT AND NOT ENABLE_THREADS STREQUAL "posix")
387         if(ENABLE_THREADS STREQUAL "win95"
388                 OR (ENABLE_THREADS STREQUAL "ON"
389                     AND CMAKE_SIZEOF_VOID_P EQUAL 4))
390             # Use Windows 95 (and thus XP) compatible threads.
391             # This avoids use of features that were added in
392             # Windows Vista. This is used for 32-bit x86 builds for
393             # compatibility reasons since it makes no measurable difference
394             # in performance compared to Vista threads.
395             set(USE_WIN95_THREADS ON)
396             add_compile_definitions(MYTHREAD_WIN95)
397         else()
398             add_compile_definitions(MYTHREAD_VISTA)
399         endif()
400     elseif(CMAKE_USE_PTHREADS_INIT)
401         if(ENABLE_THREADS STREQUAL "posix" OR ENABLE_THREADS STREQUAL "ON")
402             # The threading library only needs to be explicitly linked
403             # for posix threads, so this is needed for creating
404             # liblzma-config.cmake later.
405             set(USE_POSIX_THREADS ON)
407             target_link_libraries(liblzma Threads::Threads)
408             add_compile_definitions(MYTHREAD_POSIX)
410             # Check if pthread_condattr_setclock() exists to
411             # use CLOCK_MONOTONIC.
412             if(HAVE_CLOCK_MONOTONIC)
413                 list(INSERT CMAKE_REQUIRED_LIBRARIES 0
414                      "${CMAKE_THREAD_LIBS_INIT}")
415                 check_symbol_exists(pthread_condattr_setclock pthread.h
416                                     HAVE_PTHREAD_CONDATTR_SETCLOCK)
417                 tuklib_add_definition_if(ALL HAVE_PTHREAD_CONDATTR_SETCLOCK)
418             endif()
419         else()
420             message(SEND_ERROR
421                     "Windows threading method was requested but a compatible "
422                     "library could not be found")
423         endif()
424     else()
425         message(SEND_ERROR "No supported threading library found")
426     endif()
428     target_sources(liblzma PRIVATE
429         src/common/tuklib_cpucores.c
430         src/common/tuklib_cpucores.h
431         src/liblzma/common/hardware_cputhreads.c
432         src/liblzma/common/outqueue.c
433         src/liblzma/common/outqueue.h
434     )
435 endif()
438 ############
439 # Encoders #
440 ############
442 set(SIMPLE_FILTERS
443     x86
444     arm
445     armthumb
446     arm64
447     powerpc
448     ia64
449     sparc
452 # The SUPPORTED_FILTERS are shared between Encoders and Decoders
453 # since only lzip does not appear in both lists. lzip is a special
454 # case anyway, so it is handled separately in the Decoders section.
455 set(SUPPORTED_FILTERS
456     lzma1
457     lzma2
458     delta
459     "${SIMPLE_FILTERS}"
462 set(ENCODERS "${SUPPORTED_FILTERS}" CACHE STRING "Encoders to support")
464 # If LZMA2 is enabled, then LZMA1 must also be enabled.
465 if(NOT "lzma1" IN_LIST ENCODERS AND "lzma2" IN_LIST ENCODERS)
466     message(FATAL_ERROR "LZMA2 encoder requires that LZMA1 is also enabled")
467 endif()
469 # If LZMA1 is enabled, then at least one match finder must be enabled.
470 if(MATCH_FINDERS STREQUAL "" AND "lzma1" IN_LIST ENCODERS)
471     message(FATAL_ERROR "At least 1 match finder is required for an "
472                         "LZ-based encoder")
473 endif()
475 set(HAVE_DELTA_CODER OFF)
476 set(SIMPLE_ENCODERS OFF)
477 set(HAVE_ENCODERS OFF)
479 foreach(ENCODER IN LISTS ENCODERS)
480     if(ENCODER IN_LIST SUPPORTED_FILTERS)
481         set(HAVE_ENCODERS ON)
483         if(NOT SIMPLE_ENCODERS AND ENCODER IN_LIST SIMPLE_FILTERS)
484             set(SIMPLE_ENCODERS ON)
485         endif()
487         string(TOUPPER "${ENCODER}" ENCODER_UPPER)
488         add_compile_definitions("HAVE_ENCODER_${ENCODER_UPPER}")
489     else()
490         message(FATAL_ERROR "'${ENCODER}' is not a supported encoder")
491     endif()
492 endforeach()
494 if(HAVE_ENCODERS)
495     add_compile_definitions(HAVE_ENCODERS)
497     target_sources(liblzma PRIVATE
498         src/liblzma/common/alone_encoder.c
499         src/liblzma/common/block_buffer_encoder.c
500         src/liblzma/common/block_buffer_encoder.h
501         src/liblzma/common/block_encoder.c
502         src/liblzma/common/block_encoder.h
503         src/liblzma/common/block_header_encoder.c
504         src/liblzma/common/easy_buffer_encoder.c
505         src/liblzma/common/easy_encoder.c
506         src/liblzma/common/easy_encoder_memusage.c
507         src/liblzma/common/filter_buffer_encoder.c
508         src/liblzma/common/filter_encoder.c
509         src/liblzma/common/filter_encoder.h
510         src/liblzma/common/filter_flags_encoder.c
511         src/liblzma/common/index_encoder.c
512         src/liblzma/common/index_encoder.h
513         src/liblzma/common/stream_buffer_encoder.c
514         src/liblzma/common/stream_encoder.c
515         src/liblzma/common/stream_flags_encoder.c
516         src/liblzma/common/vli_encoder.c
517     )
519     if(ENABLE_THREADS)
520         target_sources(liblzma PRIVATE
521             src/liblzma/common/stream_encoder_mt.c
522         )
523     endif()
525     if(SIMPLE_ENCODERS)
526         target_sources(liblzma PRIVATE
527             src/liblzma/simple/simple_encoder.c
528             src/liblzma/simple/simple_encoder.h
529         )
530     endif()
532     if("lzma1" IN_LIST ENCODERS)
533         target_sources(liblzma PRIVATE
534             src/liblzma/lzma/lzma_encoder.c
535             src/liblzma/lzma/lzma_encoder.h
536             src/liblzma/lzma/lzma_encoder_optimum_fast.c
537             src/liblzma/lzma/lzma_encoder_optimum_normal.c
538             src/liblzma/lzma/lzma_encoder_private.h
539             src/liblzma/lzma/fastpos.h
540             src/liblzma/lz/lz_encoder.c
541             src/liblzma/lz/lz_encoder.h
542             src/liblzma/lz/lz_encoder_hash.h
543             src/liblzma/lz/lz_encoder_hash_table.h
544             src/liblzma/lz/lz_encoder_mf.c
545             src/liblzma/rangecoder/price.h
546             src/liblzma/rangecoder/price_table.c
547             src/liblzma/rangecoder/range_encoder.h
548         )
550         if(NOT ENABLE_SMALL)
551             target_sources(liblzma PRIVATE src/liblzma/lzma/fastpos_table.c)
552         endif()
553     endif()
555     if("lzma2" IN_LIST ENCODERS)
556         target_sources(liblzma PRIVATE
557             src/liblzma/lzma/lzma2_encoder.c
558             src/liblzma/lzma/lzma2_encoder.h
559         )
560     endif()
562     if("delta" IN_LIST ENCODERS)
563         set(HAVE_DELTA_CODER ON)
564         target_sources(liblzma PRIVATE
565             src/liblzma/delta/delta_encoder.c
566             src/liblzma/delta/delta_encoder.h
567         )
568     endif()
569 endif()
572 ############
573 # Decoders #
574 ############
576 set(DECODERS "${SUPPORTED_FILTERS}" CACHE STRING "Decoders to support")
578 set(SIMPLE_DECODERS OFF)
579 set(HAVE_DECODERS OFF)
581 foreach(DECODER IN LISTS DECODERS)
582     if(DECODER IN_LIST SUPPORTED_FILTERS)
583         set(HAVE_DECODERS ON)
585         if(NOT SIMPLE_DECODERS AND DECODER IN_LIST SIMPLE_FILTERS)
586             set(SIMPLE_DECODERS ON)
587         endif()
589         string(TOUPPER "${DECODER}" DECODER_UPPER)
590         add_compile_definitions("HAVE_DECODER_${DECODER_UPPER}")
591     else()
592         message(FATAL_ERROR "'${DECODER}' is not a supported decoder")
593     endif()
594 endforeach()
596 if(HAVE_DECODERS)
597     add_compile_definitions(HAVE_DECODERS)
599     target_sources(liblzma PRIVATE
600         src/liblzma/common/alone_decoder.c
601         src/liblzma/common/alone_decoder.h
602         src/liblzma/common/auto_decoder.c
603         src/liblzma/common/block_buffer_decoder.c
604         src/liblzma/common/block_decoder.c
605         src/liblzma/common/block_decoder.h
606         src/liblzma/common/block_header_decoder.c
607         src/liblzma/common/easy_decoder_memusage.c
608         src/liblzma/common/file_info.c
609         src/liblzma/common/filter_buffer_decoder.c
610         src/liblzma/common/filter_decoder.c
611         src/liblzma/common/filter_decoder.h
612         src/liblzma/common/filter_flags_decoder.c
613         src/liblzma/common/index_decoder.c
614         src/liblzma/common/index_decoder.h
615         src/liblzma/common/index_hash.c
616         src/liblzma/common/stream_buffer_decoder.c
617         src/liblzma/common/stream_decoder.c
618         src/liblzma/common/stream_flags_decoder.c
619         src/liblzma/common/stream_decoder.h
620         src/liblzma/common/vli_decoder.c
621     )
623     if(ENABLE_THREADS)
624         target_sources(liblzma PRIVATE
625             src/liblzma/common/stream_decoder_mt.c
626         )
627     endif()
629     if(SIMPLE_DECODERS)
630         target_sources(liblzma PRIVATE
631             src/liblzma/simple/simple_decoder.c
632             src/liblzma/simple/simple_decoder.h
633         )
634     endif()
636     if("lzma1" IN_LIST DECODERS)
637         target_sources(liblzma PRIVATE
638             src/liblzma/lzma/lzma_decoder.c
639             src/liblzma/lzma/lzma_decoder.h
640             src/liblzma/rangecoder/range_decoder.h
641             src/liblzma/lz/lz_decoder.c
642             src/liblzma/lz/lz_decoder.h
643         )
644     endif()
646     if("lzma2" IN_LIST DECODERS)
647         target_sources(liblzma PRIVATE
648             src/liblzma/lzma/lzma2_decoder.c
649             src/liblzma/lzma/lzma2_decoder.h
650         )
651     endif()
653     if("delta" IN_LIST DECODERS)
654         set(HAVE_DELTA_CODER ON)
655         target_sources(liblzma PRIVATE
656             src/liblzma/delta/delta_decoder.c
657             src/liblzma/delta/delta_decoder.h
658         )
659     endif()
660 endif()
662 # Some sources must appear if the filter is configured as either
663 # an encoder or decoder.
664 if("lzma1" IN_LIST ENCODERS OR "lzma1" IN_LIST DECODERS)
665     target_sources(liblzma PRIVATE
666         src/liblzma/rangecoder/range_common.h
667         src/liblzma/lzma/lzma_encoder_presets.c
668         src/liblzma/lzma/lzma_common.h
669     )
670 endif()
672 if(HAVE_DELTA_CODER)
673     target_sources(liblzma PRIVATE
674         src/liblzma/delta/delta_common.c
675         src/liblzma/delta/delta_common.h
676         src/liblzma/delta/delta_private.h
677     )
678 endif()
680 if(SIMPLE_ENCODERS OR SIMPLE_DECODERS)
681     target_sources(liblzma PRIVATE
682         src/liblzma/simple/simple_coder.c
683         src/liblzma/simple/simple_coder.h
684         src/liblzma/simple/simple_private.h
685     )
686 endif()
688 foreach(SIMPLE_CODER IN LISTS SIMPLE_FILTERS)
689     if(SIMPLE_CODER IN_LIST ENCODERS OR SIMPLE_CODER IN_LIST DECODERS)
690         target_sources(liblzma PRIVATE "src/liblzma/simple/${SIMPLE_CODER}.c")
691     endif()
692 endforeach()
695 #############
696 # MicroLZMA #
697 #############
699 option(MICROLZMA_ENCODER
700        "MicroLZMA encoder (needed by specific applications only)" ON)
702 option(MICROLZMA_DECODER
703        "MicroLZMA decoder (needed by specific applications only)" ON)
705 if(MICROLZMA_ENCODER)
706     if(NOT "lzma1" IN_LIST ENCODERS)
707         message(FATAL_ERROR "The LZMA1 encoder is required to support the "
708                             "MicroLZMA encoder")
709     endif()
711     target_sources(liblzma PRIVATE src/liblzma/common/microlzma_encoder.c)
712 endif()
714 if(MICROLZMA_DECODER)
715     if(NOT "lzma1" IN_LIST DECODERS)
716         message(FATAL_ERROR "The LZMA1 decoder is required to support the "
717                             "MicroLZMA decoder")
718     endif()
720     target_sources(liblzma PRIVATE src/liblzma/common/microlzma_decoder.c)
721 endif()
724 #############################
725 # lzip (.lz) format support #
726 #############################
728 option(LZIP_DECODER "Support lzip decoder" ON)
730 if(LZIP_DECODER)
731     # If lzip decoder support is requested, make sure LZMA1 decoder is enabled.
732     if(NOT "lzma1" IN_LIST DECODERS)
733         message(FATAL_ERROR "The LZMA1 decoder is required to support the "
734                             "lzip decoder")
735     endif()
737     add_compile_definitions(HAVE_LZIP_DECODER)
739     target_sources(liblzma PRIVATE
740         src/liblzma/common/lzip_decoder.c
741         src/liblzma/common/lzip_decoder.h
742     )
743 endif()
747 # Put the tuklib functions under the lzma_ namespace.
748 target_compile_definitions(liblzma PRIVATE TUKLIB_SYMBOL_PREFIX=lzma_)
749 tuklib_cpucores(liblzma)
750 tuklib_physmem(liblzma)
752 # While liblzma can be built without tuklib_cpucores or tuklib_physmem
753 # modules, the liblzma API functions lzma_cputhreads() and lzma_physmem()
754 # will then be useless (which isn't too bad but still unfortunate). Since
755 # I expect the CMake-based builds to be only used on systems that are
756 # supported by these tuklib modules, problems with these tuklib modules
757 # are considered a hard error for now. This hopefully helps to catch bugs
758 # in the CMake versions of the tuklib checks.
759 if(NOT TUKLIB_CPUCORES_FOUND OR NOT TUKLIB_PHYSMEM_FOUND)
760     # Use SEND_ERROR instead of FATAL_ERROR. If someone reports a bug,
761     # seeing the results of the remaining checks can be useful too.
762     message(SEND_ERROR
763             "tuklib_cpucores() or tuklib_physmem() failed. "
764             "Unless you really are building for a system where these "
765             "modules are not supported (unlikely), this is a bug in the "
766             "included cmake/tuklib_*.cmake files that should be fixed. "
767             "To build anyway, edit this CMakeLists.txt to ignore this error.")
768 endif()
770 # Check for __attribute__((__constructor__)) support.
771 # This needs -Werror because some compilers just warn
772 # about this being unsupported.
773 cmake_push_check_state()
774 set(CMAKE_REQUIRED_FLAGS "-Werror")
775 check_c_source_compiles("
776         __attribute__((__constructor__))
777         static void my_constructor_func(void) { return; }
778         int main(void) { return 0; }
779     "
780     HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
781 cmake_pop_check_state()
782 tuklib_add_definition_if(liblzma HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
784 # The Win95 threading lacks a thread-safe one-time initialization function.
785 # The one-time initialization is needed for crc32_small.c and crc64_small.c
786 # create the CRC tables. So if small mode is enabled, the threading mode is
787 # win95, and the compiler does not support attribute constructor, then we
788 # would end up with a multithreaded build that is thread-unsafe. As a
789 # result this configuration is not allowed.
790 if(USE_WIN95_THREADS AND ENABLE_SMALL AND NOT HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
791     message(SEND_ERROR "Threading method win95 and ENABLE_SMALL "
792                         "cannot be used at the same time with a compiler "
793                         "that doesn't support "
794                         "__attribute__((__constructor__))")
795 endif()
798 # Check for __attribute__((__ifunc__())) support.
799 # Supported values for USE_ATTR_IFUNC:
801 # auto (default) - Detect ifunc support with a compile test.
802 # ON             - Always enable ifunc.
803 # OFF            - Disable ifunc usage.
804 set(USE_ATTR_IFUNC "auto" CACHE STRING "Use __attribute__((__ifunc__())).")
806 set(SUPPORTED_USE_ATTR_IFUNC auto ON OFF)
808 if(NOT USE_ATTR_IFUNC IN_LIST SUPPORTED_USE_ATTR_IFUNC)
809     message(FATAL_ERROR "'${USE_ATTR_IFUNC}' is not a supported value for"
810                         "USE_ATTR_IFUNC")
811 endif()
813 # When USE_ATTR_IFUNC is 'auto', allow the use of __attribute__((__ifunc__()))
814 # if compiler support is detected and we are building for GNU/Linux (glibc)
815 # or FreeBSD. uClibc and musl don't support ifunc in their dynamic linkers
816 # but some compilers still accept the attribute when compiling for these
817 # C libraries, which results in broken binaries. That's why we need to
818 # check which libc is being used.
819 if(USE_ATTR_IFUNC STREQUAL "auto")
820     cmake_push_check_state()
821     set(CMAKE_REQUIRED_FLAGS "-Werror")
823     check_c_source_compiles("
824             /*
825              * Force a compilation error when not using glibc on Linux
826              * or if we are not using FreeBSD. uClibc will define
827              * __GLIBC__ but does not support ifunc, so we must have
828              * an extra check to disable with uClibc.
829              */
830             #if defined(__linux__)
831             #   include <features.h>
832             #   if !defined(__GLIBC__) || defined(__UCLIBC__)
833             compile error
834             #   endif
835             #elif !defined(__FreeBSD__)
836             compile error
837             #endif
839             static void func(void) { return; }
840             static void (*resolve_func(void)) (void) { return func; }
841             void func_ifunc(void)
842                     __attribute__((__ifunc__(\"resolve_func\")));
843             int main(void) { return 0; }
844             /*
845              * 'clang -Wall' incorrectly warns that resolve_func is
846              * unused (-Wunused-function). Correct assembly output is
847              * still produced. This problem exists at least in Clang
848              * versions 4 to 17. The following silences the bogus warning:
849              */
850             void make_clang_quiet(void);
851             void make_clang_quiet(void) { resolve_func()(); }
852         "
853         SYSTEM_SUPPORTS_IFUNC)
855         cmake_pop_check_state()
856 endif()
858 if(USE_ATTR_IFUNC STREQUAL "ON" OR SYSTEM_SUPPORTS_IFUNC)
859     tuklib_add_definitions(liblzma HAVE_FUNC_ATTRIBUTE_IFUNC)
861     if(CMAKE_C_FLAGS MATCHES "-fsanitize=")
862         message(SEND_ERROR
863                 "CMAKE_C_FLAGS or the environment variable CFLAGS "
864                 "contains '-fsanitize=' which is incompatible "
865                 "with ifunc. Use -DUSE_ATTR_IFUNC=OFF "
866                 "as an argument to 'cmake' when using '-fsanitize'.")
867     endif()
868 endif()
870 # cpuid.h
871 check_include_file(cpuid.h HAVE_CPUID_H)
872 tuklib_add_definition_if(liblzma HAVE_CPUID_H)
874 # immintrin.h:
875 check_include_file(immintrin.h HAVE_IMMINTRIN_H)
876 if(HAVE_IMMINTRIN_H)
877     target_compile_definitions(liblzma PRIVATE HAVE_IMMINTRIN_H)
879     # SSE2 intrinsics:
880     check_c_source_compiles("
881             #include <immintrin.h>
882             int main(void)
883             {
884                 __m128i x = { 0 };
885                 _mm_movemask_epi8(x);
886                 return 0;
887             }
888         "
889         HAVE__MM_MOVEMASK_EPI8)
890     tuklib_add_definition_if(liblzma HAVE__MM_MOVEMASK_EPI8)
892     # CLMUL intrinsic:
893     option(ALLOW_CLMUL_CRC "Allow carryless multiplication for CRC \
894 calculation if supported by the system" ON)
896     if(ALLOW_CLMUL_CRC)
897         check_c_source_compiles("
898                 #include <immintrin.h>
899                 #if defined(__e2k__) && __iset__ < 6
900                 #   error
901                 #endif
902                 #if (defined(__GNUC__) || defined(__clang__)) \
903                         && !defined(__EDG__)
904                 __attribute__((__target__(\"ssse3,sse4.1,pclmul\")))
905                 #endif
906                 __m128i my_clmul(__m128i a)
907                 {
908                     const __m128i b = _mm_set_epi64x(1, 2);
909                     return _mm_clmulepi64_si128(a, b, 0);
910                 }
911                 int main(void) { return 0; }
912             "
913             HAVE_USABLE_CLMUL)
915         if(HAVE_USABLE_CLMUL)
916             target_sources(liblzma PRIVATE src/liblzma/check/crc_clmul.c)
917             target_compile_definitions(liblzma PRIVATE HAVE_USABLE_CLMUL)
918         endif()
919     endif()
920 endif()
922 # Support -fvisiblity=hidden when building shared liblzma.
923 # These lines do nothing on Windows (even under Cygwin).
924 # HAVE_VISIBILITY should always be defined to 0 or 1.
925 if(BUILD_SHARED_LIBS)
926     set_target_properties(liblzma PROPERTIES C_VISIBILITY_PRESET hidden)
927     target_compile_definitions(liblzma PRIVATE HAVE_VISIBILITY=1)
928 else()
929     target_compile_definitions(liblzma PRIVATE HAVE_VISIBILITY=0)
930 endif()
932 if(WIN32)
933     if(BUILD_SHARED_LIBS)
934         # Add the Windows resource file for liblzma.dll.
935         target_sources(liblzma PRIVATE src/liblzma/liblzma_w32res.rc)
937         set_target_properties(liblzma PROPERTIES
938             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
939         )
941         # Export the public API symbols with __declspec(dllexport).
942         target_compile_definitions(liblzma PRIVATE DLL_EXPORT)
944         if(NOT MSVC)
945             # Create a DEF file. The linker puts the ordinal numbers there
946             # too so the output from the linker isn't our final file.
947             target_link_options(liblzma PRIVATE
948                                 "-Wl,--output-def,liblzma.def.in")
950             # Remove the ordinal numbers from the DEF file so that
951             # no one will create an import library that links by ordinal
952             # instead of by name. We don't maintain a DEF file so the
953             # ordinal numbers aren't stable.
954             add_custom_command(TARGET liblzma POST_BUILD
955                 COMMAND "${CMAKE_COMMAND}"
956                     -DINPUT_FILE=liblzma.def.in
957                     -DOUTPUT_FILE=liblzma.def
958                     -P
959                     "${CMAKE_CURRENT_SOURCE_DIR}/cmake/remove-ordinals.cmake"
960                 BYPRODUCTS "liblzma.def"
961                 VERBATIM)
962         endif()
963     else()
964         # Disable __declspec(dllimport) when linking against static liblzma.
965         target_compile_definitions(liblzma INTERFACE LZMA_API_STATIC)
966     endif()
967 elseif(BUILD_SHARED_LIBS AND CMAKE_SYSTEM_NAME STREQUAL "Linux")
968     # GNU/Linux-specific symbol versioning for shared liblzma.
969     # Note that adding link options doesn't affect static builds
970     # but HAVE_SYMBOL_VERSIONS_LINUX must not be used with static builds
971     # because it would put symbol versions into the static library which
972     # can cause problems. It's clearer if all symver related things are
973     # omitted when not building a shared library.
974     #
975     # NOTE: Set it explicitly to 1 to make it clear that versioning is
976     # done unconditionally in the C files.
977     target_compile_definitions(liblzma PRIVATE HAVE_SYMBOL_VERSIONS_LINUX=1)
978     target_link_options(liblzma PRIVATE
979         "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_linux.map"
980     )
981     set_target_properties(liblzma PROPERTIES
982         LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_linux.map"
983     )
984 elseif(BUILD_SHARED_LIBS AND CMAKE_SYSTEM_NAME STREQUAL "FreeBSD")
985     # Symbol versioning for shared liblzma for non-GNU/Linux.
986     # FIXME? What about Solaris?
987     target_link_options(liblzma PRIVATE
988         "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_generic.map"
989     )
990     set_target_properties(liblzma PROPERTIES
991         LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_generic.map"
992     )
993 endif()
995 set_target_properties(liblzma PROPERTIES
996     # At least for now the package versioning matches the rules used for
997     # shared library versioning (excluding development releases) so it is
998     # fine to use the package version here.
999     SOVERSION "${xz_VERSION_MAJOR}"
1000     VERSION "${xz_VERSION}"
1002     # It's liblzma.so or liblzma.dll, not libliblzma.so or lzma.dll.
1003     # Avoid the name lzma.dll because it would conflict with LZMA SDK.
1004     PREFIX ""
1005     IMPORT_PREFIX ""
1008 # Create liblzma-config-version.cmake.
1010 # FIXME: SameMajorVersion is correct for stable releases but it is wrong
1011 # for development releases where each release may have incompatible changes.
1012 include(CMakePackageConfigHelpers)
1013 write_basic_package_version_file(
1014     "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config-version.cmake"
1015     VERSION "${liblzma_VERSION}"
1016     COMPATIBILITY SameMajorVersion)
1018 # Create liblzma-config.cmake. We use this spelling instead of
1019 # liblzmaConfig.cmake to make find_package work in case insensitive
1020 # manner even with case sensitive file systems. This gives more consistent
1021 # behavior between operating systems. This optionally includes a dependency
1022 # on a threading library, so the contents are created in two separate parts.
1023 # The "second half" is always needed, so create it first.
1024 set(LZMA_CONFIG_CONTENTS
1025 "include(\"\${CMAKE_CURRENT_LIST_DIR}/liblzma-targets.cmake\")
1027 if(NOT TARGET LibLZMA::LibLZMA)
1028     # Be compatible with the spelling used by the FindLibLZMA module. This
1029     # doesn't use ALIAS because it would make CMake resolve LibLZMA::LibLZMA
1030     # to liblzma::liblzma instead of keeping the original spelling. Keeping
1031     # the original spelling is important for good FindLibLZMA compatibility.
1032     add_library(LibLZMA::LibLZMA INTERFACE IMPORTED)
1033     set_target_properties(LibLZMA::LibLZMA PROPERTIES
1034                           INTERFACE_LINK_LIBRARIES liblzma::liblzma)
1035 endif()
1038 if(USE_POSIX_THREADS)
1039     set(LZMA_CONFIG_CONTENTS
1040 "include(CMakeFindDependencyMacro)
1041 set(THREADS_PREFER_PTHREAD_FLAG TRUE)
1042 find_dependency(Threads)
1044 ${LZMA_CONFIG_CONTENTS}
1046 endif()
1048 file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config.cmake"
1049         "${LZMA_CONFIG_CONTENTS}")
1051 # Set CMAKE_INSTALL_LIBDIR and friends.
1052 include(GNUInstallDirs)
1054 # Create liblzma.pc.
1055 set(prefix "${CMAKE_INSTALL_PREFIX}")
1056 set(exec_prefix "${CMAKE_INSTALL_PREFIX}")
1057 set(libdir "${CMAKE_INSTALL_FULL_LIBDIR}")
1058 set(includedir "${CMAKE_INSTALL_FULL_INCLUDEDIR}")
1059 set(PTHREAD_CFLAGS "${CMAKE_THREAD_LIBS_INIT}")
1060 configure_file(src/liblzma/liblzma.pc.in liblzma.pc
1061                @ONLY
1062                NEWLINE_STYLE LF)
1064 # Install the library binary. The INCLUDES specifies the include path that
1065 # is exported for other projects to use but it doesn't install any files.
1066 install(TARGETS liblzma EXPORT liblzmaTargets
1067         RUNTIME  DESTINATION "${CMAKE_INSTALL_BINDIR}"
1068                  COMPONENT liblzma_Runtime
1069         LIBRARY  DESTINATION "${CMAKE_INSTALL_LIBDIR}"
1070                  COMPONENT liblzma_Runtime
1071                  NAMELINK_COMPONENT liblzma_Development
1072         ARCHIVE  DESTINATION "${CMAKE_INSTALL_LIBDIR}"
1073                  COMPONENT liblzma_Development
1074         INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
1076 # Install the liblzma API headers. These use a subdirectory so
1077 # this has to be done as a separate step.
1078 install(DIRECTORY src/liblzma/api/
1079         COMPONENT liblzma_Development
1080         DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
1081         FILES_MATCHING PATTERN "*.h")
1083 # Install the CMake files that other packages can use to find liblzma.
1084 set(liblzma_INSTALL_CMAKEDIR
1085     "${CMAKE_INSTALL_LIBDIR}/cmake/liblzma"
1086     CACHE STRING "Path to liblzma's .cmake files")
1088 install(EXPORT liblzmaTargets
1089         NAMESPACE liblzma::
1090         FILE liblzma-targets.cmake
1091         DESTINATION "${liblzma_INSTALL_CMAKEDIR}"
1092         COMPONENT liblzma_Development)
1094 install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config.cmake"
1095               "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config-version.cmake"
1096         DESTINATION "${liblzma_INSTALL_CMAKEDIR}"
1097         COMPONENT liblzma_Development)
1099 if(NOT MSVC)
1100     install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblzma.pc"
1101             DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig"
1102             COMPONENT liblzma_Development)
1103 endif()
1106 #############################################################################
1107 # libgnu (getopt_long)
1108 #############################################################################
1110 # This mirrors how the Autotools build system handles the getopt_long
1111 # replacement, calling the object library libgnu since the replacement
1112 # version comes from Gnulib.
1113 add_library(libgnu OBJECT)
1115 # CMake requires that even an object library must have at least once source
1116 # file. So we give it a header file that results in no output files.
1117 target_sources(libgnu PRIVATE lib/getopt.in.h)
1119 # The Ninja Generator requires setting the linker language since it cannot
1120 # guess the programming language of just a header file. Setting this
1121 # property avoids needing an empty .c file or an non-empty unnecessary .c
1122 # file.
1123 set_target_properties(libgnu PROPERTIES LINKER_LANGUAGE C)
1125 # Create /lib directory in the build directory and add it to the include path.
1126 file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/lib")
1127 target_include_directories(libgnu PUBLIC "${CMAKE_CURRENT_BINARY_DIR}/lib")
1129 # Include /lib from the source directory. It does no harm even if none of
1130 # the Gnulib replacements are used.
1131 target_include_directories(libgnu PUBLIC lib)
1133 # The command line tools need getopt_long in order to parse arguments. If
1134 # the system does not have a getopt_long implementation we can use the one
1135 # from Gnulib instead.
1136 check_symbol_exists(getopt_long getopt.h HAVE_GETOPT_LONG)
1138 if(NOT HAVE_GETOPT_LONG)
1139     # Set the __GETOPT_PREFIX definition to "rpl_" (replacement) to avoid
1140     # name conflicts with libc symbols. The same prefix is set if using
1141     # the Autotools build (m4/getopt.m4).
1142     target_compile_definitions(libgnu PUBLIC "__GETOPT_PREFIX=rpl_")
1144     # Create a custom copy command to copy the getopt header to the build
1145     # directory and re-copy it if it is updated. (Gnulib does it this way
1146     # because it allows choosing which .in.h files to actually use in the
1147     # build. We need just getopt.h so this is a bit overcomplicated for
1148     # a single header file only.)
1149     add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1150         COMMAND "${CMAKE_COMMAND}" -E copy
1151             "${CMAKE_CURRENT_SOURCE_DIR}/lib/getopt.in.h"
1152             "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1153         MAIN_DEPENDENCY "${CMAKE_CURRENT_SOURCE_DIR}/lib/getopt.in.h"
1154         VERBATIM)
1156     target_sources(libgnu PRIVATE
1157         lib/getopt1.c
1158         lib/getopt.c
1159         lib/getopt_int.h
1160         lib/getopt-cdefs.h
1161         lib/getopt-core.h
1162         lib/getopt-ext.h
1163         lib/getopt-pfx-core.h
1164         lib/getopt-pfx-ext.h
1165         "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1166     )
1167 endif()
1170 #############################################################################
1171 # xzdec
1172 #############################################################################
1174 if(HAVE_DECODERS AND (NOT MSVC OR MSVC_VERSION GREATER_EQUAL 1900))
1175     add_executable(xzdec
1176         src/common/sysdefs.h
1177         src/common/tuklib_common.h
1178         src/common/tuklib_config.h
1179         src/common/tuklib_exit.c
1180         src/common/tuklib_exit.h
1181         src/common/tuklib_gettext.h
1182         src/common/tuklib_progname.c
1183         src/common/tuklib_progname.h
1184         src/xzdec/xzdec.c
1185     )
1187     target_include_directories(xzdec PRIVATE
1188         src/common
1189         src/liblzma/api
1190     )
1192     target_link_libraries(xzdec PRIVATE liblzma libgnu)
1194     if(WIN32)
1195         # Add the Windows resource file for xzdec.exe.
1196         target_sources(xzdec PRIVATE src/xzdec/xzdec_w32res.rc)
1197         set_target_properties(xzdec PROPERTIES
1198             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1199         )
1200     endif()
1202     tuklib_progname(xzdec)
1204     install(TARGETS xzdec
1205             RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1206                     COMPONENT xzdec)
1208     if(UNIX)
1209         install(FILES src/xzdec/xzdec.1
1210                 DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
1211                 COMPONENT xzdec)
1212     endif()
1213 endif()
1216 #############################################################################
1217 # xz
1218 #############################################################################
1220 if(NOT MSVC OR MSVC_VERSION GREATER_EQUAL 1900)
1221     add_executable(xz
1222         src/common/mythread.h
1223         src/common/sysdefs.h
1224         src/common/tuklib_common.h
1225         src/common/tuklib_config.h
1226         src/common/tuklib_exit.c
1227         src/common/tuklib_exit.h
1228         src/common/tuklib_gettext.h
1229         src/common/tuklib_integer.h
1230         src/common/tuklib_mbstr.h
1231         src/common/tuklib_mbstr_fw.c
1232         src/common/tuklib_mbstr_width.c
1233         src/common/tuklib_open_stdxxx.c
1234         src/common/tuklib_open_stdxxx.h
1235         src/common/tuklib_progname.c
1236         src/common/tuklib_progname.h
1237         src/xz/args.c
1238         src/xz/args.h
1239         src/xz/coder.c
1240         src/xz/coder.h
1241         src/xz/file_io.c
1242         src/xz/file_io.h
1243         src/xz/hardware.c
1244         src/xz/hardware.h
1245         src/xz/main.c
1246         src/xz/main.h
1247         src/xz/message.c
1248         src/xz/message.h
1249         src/xz/mytime.c
1250         src/xz/mytime.h
1251         src/xz/options.c
1252         src/xz/options.h
1253         src/xz/private.h
1254         src/xz/signals.c
1255         src/xz/signals.h
1256         src/xz/suffix.c
1257         src/xz/suffix.h
1258         src/xz/util.c
1259         src/xz/util.h
1260     )
1262     target_include_directories(xz PRIVATE
1263         src/common
1264         src/liblzma/api
1265     )
1267     if(HAVE_DECODERS)
1268         target_sources(xz PRIVATE
1269             src/xz/list.c
1270             src/xz/list.h
1271         )
1272     endif()
1274     target_link_libraries(xz PRIVATE liblzma libgnu)
1276     target_compile_definitions(xz PRIVATE ASSUME_RAM=128)
1278     if(WIN32)
1279         # Add the Windows resource file for xz.exe.
1280         target_sources(xz PRIVATE src/xz/xz_w32res.rc)
1281         set_target_properties(xz PROPERTIES
1282             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1283         )
1284     endif()
1286     tuklib_progname(xz)
1287     tuklib_mbstr(xz)
1289     check_symbol_exists(optreset getopt.h HAVE_OPTRESET)
1290     tuklib_add_definition_if(xz HAVE_OPTRESET)
1292     check_symbol_exists(posix_fadvise fcntl.h HAVE_POSIX_FADVISE)
1293     tuklib_add_definition_if(xz HAVE_POSIX_FADVISE)
1295     # How to get file time:
1296     check_struct_has_member("struct stat" st_atim.tv_nsec
1297                             "sys/types.h;sys/stat.h"
1298                             HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1299     if(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1300         tuklib_add_definitions(xz HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1301     else()
1302         check_struct_has_member("struct stat" st_atimespec.tv_nsec
1303                                 "sys/types.h;sys/stat.h"
1304                                 HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1305         if(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1306             tuklib_add_definitions(xz HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1307         else()
1308             check_struct_has_member("struct stat" st_atimensec
1309                                     "sys/types.h;sys/stat.h"
1310                                     HAVE_STRUCT_STAT_ST_ATIMENSEC)
1311             tuklib_add_definition_if(xz HAVE_STRUCT_STAT_ST_ATIMENSEC)
1312         endif()
1313     endif()
1315     # How to set file time:
1316     check_symbol_exists(futimens "sys/types.h;sys/stat.h" HAVE_FUTIMENS)
1317     if(HAVE_FUTIMENS)
1318         tuklib_add_definitions(xz HAVE_FUTIMENS)
1319     else()
1320         check_symbol_exists(futimes "sys/time.h" HAVE_FUTIMES)
1321         if(HAVE_FUTIMES)
1322             tuklib_add_definitions(xz HAVE_FUTIMES)
1323         else()
1324             check_symbol_exists(futimesat "sys/time.h" HAVE_FUTIMESAT)
1325             if(HAVE_FUTIMESAT)
1326                 tuklib_add_definitions(xz HAVE_FUTIMESAT)
1327             else()
1328                 check_symbol_exists(utimes "sys/time.h" HAVE_UTIMES)
1329                 if(HAVE_UTIMES)
1330                     tuklib_add_definitions(xz HAVE_UTIMES)
1331                 else()
1332                     check_symbol_exists(_futime "sys/utime.h" HAVE__FUTIME)
1333                     if(HAVE__FUTIME)
1334                         tuklib_add_definitions(xz HAVE__FUTIME)
1335                     else()
1336                         check_symbol_exists(utime "utime.h" HAVE_UTIME)
1337                         tuklib_add_definition_if(xz HAVE_UTIME)
1338                     endif()
1339                 endif()
1340             endif()
1341         endif()
1342     endif()
1344     # Sandboxing:
1345     # ON        Use sandboxing if a supported method is available in the OS.
1346     # OFF       Disable sandboxing.
1347     # capsicum  Require Capsicum (FreeBSD >= 10.2) and fail if not found.
1348     # pledge    Require pledge(2) (OpenBSD >= 5.9) and fail if not found.
1349     # landlock  Require Landlock (Linux >= 5.13) and fail if not found.
1350     set(SUPPORTED_SANDBOX_METHODS ON OFF capsicum pledge landlock)
1352     set(ENABLE_SANDBOX ON CACHE STRING "Sandboxing method to use in 'xz'")
1354     set_property(CACHE ENABLE_SANDBOX
1355                  PROPERTY STRINGS "${SUPPORTED_SANDBOX_METHODS}")
1357     if(NOT ENABLE_SANDBOX IN_LIST SUPPORTED_SANDBOX_METHODS)
1358         message(FATAL_ERROR "'${ENABLE_SANDBOX}' is not a supported "
1359                             "sandboxing method")
1360     endif()
1362     # When autodetecting, the search order is fixed and we must not find
1363     # more than one method.
1364     if(ENABLE_SANDBOX STREQUAL "OFF")
1365         set(SANDBOX_FOUND ON)
1366     else()
1367         set(SANDBOX_FOUND OFF)
1368     endif()
1370     # Sandboxing: Capsicum
1371     if(NOT SANDBOX_FOUND AND ENABLE_SANDBOX MATCHES "^ON$|^capsicum$")
1372         check_symbol_exists(cap_rights_limit sys/capsicum.h
1373                             HAVE_CAP_RIGHTS_LIMIT)
1374         if(HAVE_CAP_RIGHTS_LIMIT)
1375             target_compile_definitions(xz PRIVATE HAVE_CAP_RIGHTS_LIMIT)
1376             set(SANDBOX_FOUND ON)
1377         endif()
1378     endif()
1380     # Sandboxing: pledge(2)
1381     if(NOT SANDBOX_FOUND AND ENABLE_SANDBOX MATCHES "^ON$|^pledge$")
1382         check_symbol_exists(pledge unistd.h HAVE_PLEDGE)
1383         if(HAVE_PLEDGE)
1384             target_compile_definitions(xz PRIVATE HAVE_PLEDGE)
1385             set(SANDBOX_FOUND ON)
1386         endif()
1387     endif()
1389     # Sandboxing: Landlock
1390     if(NOT SANDBOX_FOUND AND ENABLE_SANDBOX MATCHES "^ON$|^landlock$")
1391         check_include_file(linux/landlock.h HAVE_LINUX_LANDLOCK_H)
1393         if(HAVE_LINUX_LANDLOCK_H)
1394             target_compile_definitions(xz PRIVATE HAVE_LINUX_LANDLOCK_H)
1395             set(SANDBOX_FOUND ON)
1397             # Of our three sandbox methods, only Landlock is incompatible
1398             # with -fsanitize. FreeBSD 13.2 with Capsicum was tested with
1399             # -fsanitize=address,undefined and had no issues. OpenBSD (as
1400             # of version 7.4) has minimal support for process instrumentation.
1401             # OpenBSD does not distribute the additional libraries needed
1402             # (libasan, libubsan, etc.) with GCC or Clang needed for runtime
1403             # sanitization support and instead only support
1404             # -fsanitize-minimal-runtime for minimal undefined behavior
1405             # sanitization. This minimal support is compatible with our use
1406             # of the Pledge sandbox. So only Landlock will result in a
1407             # build that cannot compress or decompress a single file to
1408             # standard out.
1409             if(CMAKE_C_FLAGS MATCHES "-fsanitize=")
1410                 message(SEND_ERROR
1411                         "CMAKE_C_FLAGS or the environment variable CFLAGS "
1412                         "contains '-fsanitize=' which is incompatible "
1413                         "with Landlock sandboxing. Use -DENABLE_SANDBOX=OFF "
1414                         "as an argument to 'cmake' when using '-fsanitize'.")
1415             endif()
1416         endif()
1417     endif()
1419     if(NOT SANDBOX_FOUND AND NOT ENABLE_SANDBOX MATCHES "^ON$|^OFF$")
1420         message(SEND_ERROR "ENABLE_SANDBOX=${ENABLE_SANDBOX} was used but "
1421                            "support for the sandboxing method wasn't found.")
1422     endif()
1424     install(TARGETS xz
1425             RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1426                     COMPONENT xz)
1428     if(UNIX)
1429         install(FILES src/xz/xz.1
1430                 DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
1431                 COMPONENT xz)
1433         option(CREATE_XZ_SYMLINKS "Create unxz and xzcat symlinks" ON)
1434         option(CREATE_LZMA_SYMLINKS "Create lzma, unlzma, and lzcat symlinks"
1435                ON)
1436         set(XZ_LINKS)
1438         if(CREATE_XZ_SYMLINKS)
1439             list(APPEND XZ_LINKS "unxz" "xzcat")
1440         endif()
1442         if(CREATE_LZMA_SYMLINKS)
1443             list(APPEND XZ_LINKS "lzma" "unlzma" "lzcat")
1444         endif()
1446         # With Windows Cygwin and MSYS2 the symlinking is complicated. Both
1447         # of these environments set the UNIX variable so they will try to
1448         # make the symlinks. The ability for Cygwin and MSYS2 to make
1449         # broken symlinks is determined by the CYGWIN and MSYS2 environment
1450         # variables, respectively. Broken symlinks are needed for the man
1451         # page symlinks and for determining if the xz and lzma symlinks need
1452         # to depend on the xz target or not. If broken symlinks cannot be
1453         # made then the xz binary must be created before the symlinks.
1454         set(ALLOW_BROKEN_SYMLINKS ON)
1456         if(CMAKE_SYSTEM_NAME STREQUAL "CYGWIN")
1457             # The Cygwin env variable can be set to four possible values:
1458             #
1459             # 1. "lnk". Create symlinks as Windows shortcuts.
1460             #
1461             # 2. "native". Create symlinks as native Windows symlinks
1462             #    if supported by the system. Fallback to "lnk" if native
1463             #    symlinks are not supported.
1464             #
1465             # 3. "nativestrict". Create symlinks as native Windows symlinks
1466             #    if supported by the system. If the target of the symlink
1467             #    does not exist or the creation of the symlink fails for any
1468             #    reason, do not create the symlink.
1469             #
1470             # 4. "sys". Create symlinks as plain files with a special
1471             #    system attribute containing the path to the symlink target.
1472             #
1473             # So, the only case we care about for broken symlinks is
1474             # "nativestrict" since all other values mean that broken
1475             # symlinks are allowed. If the env variable is not set the
1476             # default is "native". If the env variable is set but not
1477             # assigned one of the four values, then the default is the same
1478             # as option 1 "lnk".
1479             string(FIND "$ENV{CYGWIN}" "winsymlinks:nativestrict" SYMLINK_POS)
1480             if(SYMLINK_POS GREATER -1)
1481                 set(ALLOW_BROKEN_SYMLINKS OFF)
1482             endif()
1483         elseif(CMAKE_SYSTEM_NAME STREQUAL "MSYS")
1484             # The MSYS env variable behaves similar to the CYGWIN but has a
1485             # different default behavior. If winsymlinks is set but not
1486             # assigned one of the four supported values, the default is to
1487             # *copy* the target to the symlink destination. This will fail
1488             # if the target does not exist so broken symlinks cannot be
1489             # allowed.
1490             string(FIND "$ENV{MSYS}" "winsymlinks" SYMLINK_POS)
1491             if(SYMLINK_POS GREATER -1)
1492                 string(FIND "$ENV{MSYS}" "winsymlinks:nativestrict"
1493                         SYMLINK_POS)
1494                 if(SYMLINK_POS GREATER -1)
1495                     set(ALLOW_BROKEN_SYMLINKS OFF)
1496                 endif()
1497             else()
1498                 set(ALLOW_BROKEN_SYMLINKS OFF)
1499             endif()
1500         endif()
1502         # Create symlinks in the build directory and then install them.
1503         #
1504         # The symlinks do not likely need any special extension since
1505         # even on Windows the symlink can still be executed without
1506         # the .exe extension.
1507         foreach(LINK IN LISTS XZ_LINKS)
1508             add_custom_target("create_${LINK}" ALL
1509                 "${CMAKE_COMMAND}" -E create_symlink
1510                     "$<TARGET_FILE_NAME:xz>" "${LINK}"
1511                 BYPRODUCTS "${LINK}"
1512                 VERBATIM)
1513             install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${LINK}"
1514                     DESTINATION "${CMAKE_INSTALL_BINDIR}"
1515                     COMPONENT xz)
1517             # Only create the man page symlinks if the symlinks can be
1518             # created broken. The symlinks will not be valid until install
1519             # so they cannot be created on these system environments.
1520             if(ALLOW_BROKEN_SYMLINKS)
1521                 add_custom_target("create_${LINK}.1" ALL
1522                     "${CMAKE_COMMAND}" -E create_symlink "xz.1" "${LINK}.1"
1523                     BYPRODUCTS "${LINK}.1"
1524                     VERBATIM)
1525                 install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${LINK}.1"
1526                         DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
1527                         COMPONENT xz)
1528             else()
1529                 # Add the xz target as dependency when broken symlinks
1530                 # cannot be made. This ensures parallel builds do not fail
1531                 # since it will enforce the order of creating xz first, then
1532                 # the symlinks.
1533                 add_dependencies("create_${LINK}" xz)
1534             endif()
1535         endforeach()
1536     endif()
1537 endif()
1540 #############################################################################
1541 # Tests
1542 #############################################################################
1544 include(CTest)
1546 if(BUILD_TESTING)
1547     set(LIBLZMA_TESTS
1548         test_bcj_exact_size
1549         test_block_header
1550         test_check
1551         test_filter_flags
1552         test_filter_str
1553         test_hardware
1554         test_index
1555         test_index_hash
1556         test_lzip_decoder
1557         test_memlimit
1558         test_stream_flags
1559         test_vli
1560     )
1562     foreach(TEST IN LISTS LIBLZMA_TESTS)
1563         add_executable("${TEST}" "tests/${TEST}.c")
1565         target_include_directories("${TEST}" PRIVATE
1566             src/common
1567             src/liblzma/api
1568             src/liblzma
1569         )
1571         target_link_libraries("${TEST}" PRIVATE liblzma)
1573         # Put the test programs into their own subdirectory so they don't
1574         # pollute the top-level dir which might contain xz and xzdec.
1575         set_target_properties("${TEST}" PROPERTIES
1576             RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/tests_bin"
1577         )
1579         add_test(NAME "${TEST}"
1580                  COMMAND "${CMAKE_CURRENT_BINARY_DIR}/tests_bin/${TEST}"
1581         )
1583         # Set srcdir environment variable so that the tests find their
1584         # input files from the source tree.
1585         #
1586         # Set the return code for skipped tests to match Automake convention.
1587         set_tests_properties("${TEST}" PROPERTIES
1588             ENVIRONMENT "srcdir=${CMAKE_CURRENT_SOURCE_DIR}/tests"
1589             SKIP_RETURN_CODE 77
1590         )
1591     endforeach()
1592 endif()