Add NEWS for 5.4.6.
[xz.git] / CMakeLists.txt
blobc5573d7b32a07604d5d41044098df09d50c7d49d
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://xz.tukaani.org/xz-utils/")
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/check/crc_x86_clmul.h
233     src/liblzma/common/block_util.c
234     src/liblzma/common/common.c
235     src/liblzma/common/common.h
236     src/liblzma/common/easy_preset.c
237     src/liblzma/common/easy_preset.h
238     src/liblzma/common/filter_common.c
239     src/liblzma/common/filter_common.h
240     src/liblzma/common/hardware_physmem.c
241     src/liblzma/common/index.c
242     src/liblzma/common/index.h
243     src/liblzma/common/memcmplen.h
244     src/liblzma/common/stream_flags_common.c
245     src/liblzma/common/stream_flags_common.h
246     src/liblzma/common/string_conversion.c
247     src/liblzma/common/vli_size.c
250 target_include_directories(liblzma PRIVATE
251     src/liblzma/api
252     src/liblzma/common
253     src/liblzma/check
254     src/liblzma/lz
255     src/liblzma/rangecoder
256     src/liblzma/lzma
257     src/liblzma/delta
258     src/liblzma/simple
259     src/common
263 ######################
264 # Size optimizations #
265 ######################
267 option(ENABLE_SMALL "Reduce code size at expense of speed. \
268 This may be useful together with CMAKE_BUILD_TYPE=MinSizeRel.")
270 if(ENABLE_SMALL)
271     add_compile_definitions(HAVE_SMALL)
272 endif()
275 ##########
276 # Checks #
277 ##########
279 set(ADDITIONAL_SUPPORTED_CHECKS crc64 sha256)
281 set(ADDITIONAL_CHECK_TYPES "${ADDITIONAL_SUPPORTED_CHECKS}" CACHE STRING
282     "Additional check types to support (crc32 is always built)")
284 foreach(CHECK IN LISTS ADDITIONAL_CHECK_TYPES)
285     if(NOT CHECK IN_LIST ADDITIONAL_SUPPORTED_CHECKS)
286         message(FATAL_ERROR "'${CHECK}' is not a supported check type")
287     endif()
288 endforeach()
290 if(ENABLE_SMALL)
291     target_sources(liblzma PRIVATE src/liblzma/check/crc32_small.c)
292 else()
293     target_sources(liblzma PRIVATE
294         src/liblzma/check/crc32_fast.c
295         src/liblzma/check/crc32_table.c
296         src/liblzma/check/crc32_table_be.h
297         src/liblzma/check/crc32_table_le.h
298     )
299 endif()
301 if("crc64" IN_LIST ADDITIONAL_CHECK_TYPES)
302     add_compile_definitions("HAVE_CHECK_CRC64")
304     if(ENABLE_SMALL)
305         target_sources(liblzma PRIVATE src/liblzma/check/crc64_small.c)
306     else()
307         target_sources(liblzma PRIVATE
308             src/liblzma/check/crc64_fast.c
309             src/liblzma/check/crc64_table.c
310             src/liblzma/check/crc64_table_be.h
311             src/liblzma/check/crc64_table_le.h
312         )
313     endif()
314 endif()
316 if("sha256" IN_LIST ADDITIONAL_CHECK_TYPES)
317     add_compile_definitions("HAVE_CHECK_SHA256")
318     target_sources(liblzma PRIVATE src/liblzma/check/sha256.c)
319 endif()
322 #################
323 # Match finders #
324 #################
326 set(SUPPORTED_MATCH_FINDERS hc3 hc4 bt2 bt3 bt4)
328 set(MATCH_FINDERS "${SUPPORTED_MATCH_FINDERS}" CACHE STRING
329     "Match finders to support (at least one is required for LZMA1 or LZMA2)")
331 foreach(MF IN LISTS MATCH_FINDERS)
332     if(MF IN_LIST SUPPORTED_MATCH_FINDERS)
333         string(TOUPPER "${MF}" MF_UPPER)
334         add_compile_definitions("HAVE_MF_${MF_UPPER}")
335     else()
336         message(FATAL_ERROR "'${MF}' is not a supported match finder")
337     endif()
338 endforeach()
341 #############
342 # Threading #
343 #############
345 # Supported threading methods:
346 # ON    - autodetect the best threading method. The autodetection will
347 #         prefer Windows threading (win95 or vista) over posix if both are
348 #         available. vista threads will be used over win95 unless it is a
349 #         32-bit build.
350 # OFF   - Disable threading.
351 # posix - Use posix threading (pthreads), or throw an error if not available.
352 # win95 - Use Windows win95 threading, or throw an error if not available.
353 # vista - Use Windows vista threading, or throw an error if not available.
354 set(SUPPORTED_THREADING_METHODS ON OFF posix win95 vista)
356 set(ENABLE_THREADS ON CACHE STRING
357     "Threading method: Set to 'ON' to autodetect, 'OFF' to disable threading.")
359 # Create dropdown in CMake GUI since only 1 threading method is possible
360 # to select in a build.
361 set_property(CACHE ENABLE_THREADS
362              PROPERTY STRINGS "${SUPPORTED_THREADING_METHODS}")
364 # This is a flag variable set when win95 threads are used. We must ensure
365 # the combination of enable_small and win95 threads is not used without a
366 # compiler supporting attribute __constructor__.
367 set(USE_WIN95_THREADS OFF)
369 # This is a flag variable set when posix threads (pthreads) are used.
370 # It's needed when creating liblzma-config.cmake where dependency on
371 # Threads::Threads is only needed with pthreads.
372 set(USE_POSIX_THREADS OFF)
374 if(NOT ENABLE_THREADS IN_LIST SUPPORTED_THREADING_METHODS)
375     message(FATAL_ERROR "'${ENABLE_THREADS}' is not a supported "
376                         "threading method")
377 endif()
379 if(ENABLE_THREADS)
380     # Also set THREADS_PREFER_PTHREAD_FLAG since the flag has no effect
381     # for Windows threading.
382     set(THREADS_PREFER_PTHREAD_FLAG TRUE)
383     find_package(Threads REQUIRED)
385     # If both Windows and posix threading are available, prefer Windows.
386     # Note that on Cygwin CMAKE_USE_WIN32_THREADS_INIT is false.
387     if(CMAKE_USE_WIN32_THREADS_INIT AND NOT ENABLE_THREADS STREQUAL "posix")
388         if(ENABLE_THREADS STREQUAL "win95"
389                 OR (ENABLE_THREADS STREQUAL "ON"
390                     AND CMAKE_SIZEOF_VOID_P EQUAL 4))
391             # Use Windows 95 (and thus XP) compatible threads.
392             # This avoids use of features that were added in
393             # Windows Vista. This is used for 32-bit x86 builds for
394             # compatibility reasons since it makes no measurable difference
395             # in performance compared to Vista threads.
396             set(USE_WIN95_THREADS ON)
397             add_compile_definitions(MYTHREAD_WIN95)
398         else()
399             add_compile_definitions(MYTHREAD_VISTA)
400         endif()
401     elseif(CMAKE_USE_PTHREADS_INIT)
402         if(ENABLE_THREADS STREQUAL "posix" OR ENABLE_THREADS STREQUAL "ON")
403             # The threading library only needs to be explicitly linked
404             # for posix threads, so this is needed for creating
405             # liblzma-config.cmake later.
406             set(USE_POSIX_THREADS ON)
408             target_link_libraries(liblzma Threads::Threads)
409             add_compile_definitions(MYTHREAD_POSIX)
411             # Check if pthread_condattr_setclock() exists to
412             # use CLOCK_MONOTONIC.
413             if(HAVE_CLOCK_MONOTONIC)
414                 list(INSERT CMAKE_REQUIRED_LIBRARIES 0
415                      "${CMAKE_THREAD_LIBS_INIT}")
416                 check_symbol_exists(pthread_condattr_setclock pthread.h
417                                     HAVE_PTHREAD_CONDATTR_SETCLOCK)
418                 tuklib_add_definition_if(ALL HAVE_PTHREAD_CONDATTR_SETCLOCK)
419             endif()
420         else()
421             message(SEND_ERROR
422                     "Windows threading method was requested but a compatible "
423                     "library could not be found")
424         endif()
425     else()
426         message(SEND_ERROR "No supported threading library found")
427     endif()
429     target_sources(liblzma PRIVATE
430         src/common/tuklib_cpucores.c
431         src/common/tuklib_cpucores.h
432         src/liblzma/common/hardware_cputhreads.c
433         src/liblzma/common/outqueue.c
434         src/liblzma/common/outqueue.h
435     )
436 endif()
439 ############
440 # Encoders #
441 ############
443 set(SIMPLE_FILTERS
444     x86
445     arm
446     armthumb
447     arm64
448     powerpc
449     ia64
450     sparc
451     riscv
454 # The SUPPORTED_FILTERS are shared between Encoders and Decoders
455 # since only lzip does not appear in both lists. lzip is a special
456 # case anyway, so it is handled separately in the Decoders section.
457 set(SUPPORTED_FILTERS
458     lzma1
459     lzma2
460     delta
461     "${SIMPLE_FILTERS}"
464 set(ENCODERS "${SUPPORTED_FILTERS}" CACHE STRING "Encoders to support")
466 # If LZMA2 is enabled, then LZMA1 must also be enabled.
467 if(NOT "lzma1" IN_LIST ENCODERS AND "lzma2" IN_LIST ENCODERS)
468     message(FATAL_ERROR "LZMA2 encoder requires that LZMA1 is also enabled")
469 endif()
471 # If LZMA1 is enabled, then at least one match finder must be enabled.
472 if(MATCH_FINDERS STREQUAL "" AND "lzma1" IN_LIST ENCODERS)
473     message(FATAL_ERROR "At least 1 match finder is required for an "
474                         "LZ-based encoder")
475 endif()
477 set(HAVE_DELTA_CODER OFF)
478 set(SIMPLE_ENCODERS OFF)
479 set(HAVE_ENCODERS OFF)
481 foreach(ENCODER IN LISTS ENCODERS)
482     if(ENCODER IN_LIST SUPPORTED_FILTERS)
483         set(HAVE_ENCODERS ON)
485         if(NOT SIMPLE_ENCODERS AND ENCODER IN_LIST SIMPLE_FILTERS)
486             set(SIMPLE_ENCODERS ON)
487         endif()
489         string(TOUPPER "${ENCODER}" ENCODER_UPPER)
490         add_compile_definitions("HAVE_ENCODER_${ENCODER_UPPER}")
491     else()
492         message(FATAL_ERROR "'${ENCODER}' is not a supported encoder")
493     endif()
494 endforeach()
496 if(HAVE_ENCODERS)
497     add_compile_definitions(HAVE_ENCODERS)
499     target_sources(liblzma PRIVATE
500         src/liblzma/common/alone_encoder.c
501         src/liblzma/common/block_buffer_encoder.c
502         src/liblzma/common/block_buffer_encoder.h
503         src/liblzma/common/block_encoder.c
504         src/liblzma/common/block_encoder.h
505         src/liblzma/common/block_header_encoder.c
506         src/liblzma/common/easy_buffer_encoder.c
507         src/liblzma/common/easy_encoder.c
508         src/liblzma/common/easy_encoder_memusage.c
509         src/liblzma/common/filter_buffer_encoder.c
510         src/liblzma/common/filter_encoder.c
511         src/liblzma/common/filter_encoder.h
512         src/liblzma/common/filter_flags_encoder.c
513         src/liblzma/common/index_encoder.c
514         src/liblzma/common/index_encoder.h
515         src/liblzma/common/stream_buffer_encoder.c
516         src/liblzma/common/stream_encoder.c
517         src/liblzma/common/stream_flags_encoder.c
518         src/liblzma/common/vli_encoder.c
519     )
521     if(ENABLE_THREADS)
522         target_sources(liblzma PRIVATE
523             src/liblzma/common/stream_encoder_mt.c
524         )
525     endif()
527     if(SIMPLE_ENCODERS)
528         target_sources(liblzma PRIVATE
529             src/liblzma/simple/simple_encoder.c
530             src/liblzma/simple/simple_encoder.h
531         )
532     endif()
534     if("lzma1" IN_LIST ENCODERS)
535         target_sources(liblzma PRIVATE
536             src/liblzma/lzma/lzma_encoder.c
537             src/liblzma/lzma/lzma_encoder.h
538             src/liblzma/lzma/lzma_encoder_optimum_fast.c
539             src/liblzma/lzma/lzma_encoder_optimum_normal.c
540             src/liblzma/lzma/lzma_encoder_private.h
541             src/liblzma/lzma/fastpos.h
542             src/liblzma/lz/lz_encoder.c
543             src/liblzma/lz/lz_encoder.h
544             src/liblzma/lz/lz_encoder_hash.h
545             src/liblzma/lz/lz_encoder_hash_table.h
546             src/liblzma/lz/lz_encoder_mf.c
547             src/liblzma/rangecoder/price.h
548             src/liblzma/rangecoder/price_table.c
549             src/liblzma/rangecoder/range_encoder.h
550         )
552         if(NOT ENABLE_SMALL)
553             target_sources(liblzma PRIVATE src/liblzma/lzma/fastpos_table.c)
554         endif()
555     endif()
557     if("lzma2" IN_LIST ENCODERS)
558         target_sources(liblzma PRIVATE
559             src/liblzma/lzma/lzma2_encoder.c
560             src/liblzma/lzma/lzma2_encoder.h
561         )
562     endif()
564     if("delta" IN_LIST ENCODERS)
565         set(HAVE_DELTA_CODER ON)
566         target_sources(liblzma PRIVATE
567             src/liblzma/delta/delta_encoder.c
568             src/liblzma/delta/delta_encoder.h
569         )
570     endif()
571 endif()
574 ############
575 # Decoders #
576 ############
578 set(DECODERS "${SUPPORTED_FILTERS}" CACHE STRING "Decoders to support")
580 set(SIMPLE_DECODERS OFF)
581 set(HAVE_DECODERS OFF)
583 foreach(DECODER IN LISTS DECODERS)
584     if(DECODER IN_LIST SUPPORTED_FILTERS)
585         set(HAVE_DECODERS ON)
587         if(NOT SIMPLE_DECODERS AND DECODER IN_LIST SIMPLE_FILTERS)
588             set(SIMPLE_DECODERS ON)
589         endif()
591         string(TOUPPER "${DECODER}" DECODER_UPPER)
592         add_compile_definitions("HAVE_DECODER_${DECODER_UPPER}")
593     else()
594         message(FATAL_ERROR "'${DECODER}' is not a supported decoder")
595     endif()
596 endforeach()
598 if(HAVE_DECODERS)
599     add_compile_definitions(HAVE_DECODERS)
601     target_sources(liblzma PRIVATE
602         src/liblzma/common/alone_decoder.c
603         src/liblzma/common/alone_decoder.h
604         src/liblzma/common/auto_decoder.c
605         src/liblzma/common/block_buffer_decoder.c
606         src/liblzma/common/block_decoder.c
607         src/liblzma/common/block_decoder.h
608         src/liblzma/common/block_header_decoder.c
609         src/liblzma/common/easy_decoder_memusage.c
610         src/liblzma/common/file_info.c
611         src/liblzma/common/filter_buffer_decoder.c
612         src/liblzma/common/filter_decoder.c
613         src/liblzma/common/filter_decoder.h
614         src/liblzma/common/filter_flags_decoder.c
615         src/liblzma/common/index_decoder.c
616         src/liblzma/common/index_decoder.h
617         src/liblzma/common/index_hash.c
618         src/liblzma/common/stream_buffer_decoder.c
619         src/liblzma/common/stream_decoder.c
620         src/liblzma/common/stream_flags_decoder.c
621         src/liblzma/common/stream_decoder.h
622         src/liblzma/common/vli_decoder.c
623     )
625     if(ENABLE_THREADS)
626         target_sources(liblzma PRIVATE
627             src/liblzma/common/stream_decoder_mt.c
628         )
629     endif()
631     if(SIMPLE_DECODERS)
632         target_sources(liblzma PRIVATE
633             src/liblzma/simple/simple_decoder.c
634             src/liblzma/simple/simple_decoder.h
635         )
636     endif()
638     if("lzma1" IN_LIST DECODERS)
639         target_sources(liblzma PRIVATE
640             src/liblzma/lzma/lzma_decoder.c
641             src/liblzma/lzma/lzma_decoder.h
642             src/liblzma/rangecoder/range_decoder.h
643             src/liblzma/lz/lz_decoder.c
644             src/liblzma/lz/lz_decoder.h
645         )
646     endif()
648     if("lzma2" IN_LIST DECODERS)
649         target_sources(liblzma PRIVATE
650             src/liblzma/lzma/lzma2_decoder.c
651             src/liblzma/lzma/lzma2_decoder.h
652         )
653     endif()
655     if("delta" IN_LIST DECODERS)
656         set(HAVE_DELTA_CODER ON)
657         target_sources(liblzma PRIVATE
658             src/liblzma/delta/delta_decoder.c
659             src/liblzma/delta/delta_decoder.h
660         )
661     endif()
662 endif()
664 # Some sources must appear if the filter is configured as either
665 # an encoder or decoder.
666 if("lzma1" IN_LIST ENCODERS OR "lzma1" IN_LIST DECODERS)
667     target_sources(liblzma PRIVATE
668         src/liblzma/rangecoder/range_common.h
669         src/liblzma/lzma/lzma_encoder_presets.c
670         src/liblzma/lzma/lzma_common.h
671     )
672 endif()
674 if(HAVE_DELTA_CODER)
675     target_sources(liblzma PRIVATE
676         src/liblzma/delta/delta_common.c
677         src/liblzma/delta/delta_common.h
678         src/liblzma/delta/delta_private.h
679     )
680 endif()
682 if(SIMPLE_ENCODERS OR SIMPLE_DECODERS)
683     target_sources(liblzma PRIVATE
684         src/liblzma/simple/simple_coder.c
685         src/liblzma/simple/simple_coder.h
686         src/liblzma/simple/simple_private.h
687     )
688 endif()
690 foreach(SIMPLE_CODER IN LISTS SIMPLE_FILTERS)
691     if(SIMPLE_CODER IN_LIST ENCODERS OR SIMPLE_CODER IN_LIST DECODERS)
692         target_sources(liblzma PRIVATE "src/liblzma/simple/${SIMPLE_CODER}.c")
693     endif()
694 endforeach()
697 #############
698 # MicroLZMA #
699 #############
701 option(MICROLZMA_ENCODER
702        "MicroLZMA encoder (needed by specific applications only)" ON)
704 option(MICROLZMA_DECODER
705        "MicroLZMA decoder (needed by specific applications only)" ON)
707 if(MICROLZMA_ENCODER)
708     if(NOT "lzma1" IN_LIST ENCODERS)
709         message(FATAL_ERROR "The LZMA1 encoder is required to support the "
710                             "MicroLZMA encoder")
711     endif()
713     target_sources(liblzma PRIVATE src/liblzma/common/microlzma_encoder.c)
714 endif()
716 if(MICROLZMA_DECODER)
717     if(NOT "lzma1" IN_LIST DECODERS)
718         message(FATAL_ERROR "The LZMA1 decoder is required to support the "
719                             "MicroLZMA decoder")
720     endif()
722     target_sources(liblzma PRIVATE src/liblzma/common/microlzma_decoder.c)
723 endif()
726 #############################
727 # lzip (.lz) format support #
728 #############################
730 option(LZIP_DECODER "Support lzip decoder" ON)
732 if(LZIP_DECODER)
733     # If lzip decoder support is requested, make sure LZMA1 decoder is enabled.
734     if(NOT "lzma1" IN_LIST DECODERS)
735         message(FATAL_ERROR "The LZMA1 decoder is required to support the "
736                             "lzip decoder")
737     endif()
739     add_compile_definitions(HAVE_LZIP_DECODER)
741     target_sources(liblzma PRIVATE
742         src/liblzma/common/lzip_decoder.c
743         src/liblzma/common/lzip_decoder.h
744     )
745 endif()
748 ##############
749 # Sandboxing #
750 ##############
752 # ON        Use sandboxing if a supported method is available in the OS.
753 # OFF       Disable sandboxing.
754 # capsicum  Require Capsicum (FreeBSD >= 10.2) and fail if not found.
755 # pledge    Require pledge(2) (OpenBSD >= 5.9) and fail if not found.
756 # landlock  Require Landlock (Linux >= 5.13) and fail if not found.
757 set(SUPPORTED_SANDBOX_METHODS ON OFF capsicum pledge landlock)
759 set(ENABLE_SANDBOX ON CACHE STRING
760     "Sandboxing method to use in 'xz' and 'xzdec'")
762 set_property(CACHE ENABLE_SANDBOX
763                 PROPERTY STRINGS "${SUPPORTED_SANDBOX_METHODS}")
765 if(NOT ENABLE_SANDBOX IN_LIST SUPPORTED_SANDBOX_METHODS)
766     message(FATAL_ERROR "'${ENABLE_SANDBOX}' is not a supported "
767                         "sandboxing method")
768 endif()
770 # When autodetecting, the search order is fixed and we must not find
771 # more than one method.
772 if(ENABLE_SANDBOX STREQUAL "OFF")
773     set(SANDBOX_FOUND ON)
774 else()
775     set(SANDBOX_FOUND OFF)
776 endif()
778 # Since xz and xzdec can both use sandboxing, the compile definition needed
779 # to use the sandbox must be added to both targets.
780 set(SANDBOX_COMPILE_DEFINITION OFF)
782 # Sandboxing: Capsicum
783 if(NOT SANDBOX_FOUND AND ENABLE_SANDBOX MATCHES "^ON$|^capsicum$")
784     check_symbol_exists(cap_rights_limit sys/capsicum.h
785                         HAVE_CAP_RIGHTS_LIMIT)
786     if(HAVE_CAP_RIGHTS_LIMIT)
787         set(SANDBOX_COMPILE_DEFINITION "HAVE_CAP_RIGHTS_LIMIT")
788         set(SANDBOX_FOUND ON)
789     endif()
790 endif()
792 # Sandboxing: pledge(2)
793 if(NOT SANDBOX_FOUND AND ENABLE_SANDBOX MATCHES "^ON$|^pledge$")
794     check_symbol_exists(pledge unistd.h HAVE_PLEDGE)
795     if(HAVE_PLEDGE)
796         set(SANDBOX_COMPILE_DEFINITION "HAVE_PLEDGE")
797         set(SANDBOX_FOUND ON)
798     endif()
799 endif()
801 # Sandboxing: Landlock
802 if(NOT SANDBOX_FOUND AND ENABLE_SANDBOX MATCHES "^ON$|^landlock$")
803     check_include_file(linux/landlock.h HAVE_LINUX_LANDLOCK_H)
805     if(HAVE_LINUX_LANDLOCK_H)
806         set(SANDBOX_COMPILE_DEFINITION "HAVE_LINUX_LANDLOCK_H")
807         set(SANDBOX_FOUND ON)
809         # Of our three sandbox methods, only Landlock is incompatible
810         # with -fsanitize. FreeBSD 13.2 with Capsicum was tested with
811         # -fsanitize=address,undefined and had no issues. OpenBSD (as
812         # of version 7.4) has minimal support for process instrumentation.
813         # OpenBSD does not distribute the additional libraries needed
814         # (libasan, libubsan, etc.) with GCC or Clang needed for runtime
815         # sanitization support and instead only support
816         # -fsanitize-minimal-runtime for minimal undefined behavior
817         # sanitization. This minimal support is compatible with our use
818         # of the Pledge sandbox. So only Landlock will result in a
819         # build that cannot compress or decompress a single file to
820         # standard out.
821         if(CMAKE_C_FLAGS MATCHES "-fsanitize=")
822             message(SEND_ERROR
823                     "CMAKE_C_FLAGS or the environment variable CFLAGS "
824                     "contains '-fsanitize=' which is incompatible "
825                     "with Landlock sandboxing. Use -DENABLE_SANDBOX=OFF "
826                     "as an argument to 'cmake' when using '-fsanitize'.")
827         endif()
828     endif()
829 endif()
831 if(NOT SANDBOX_FOUND AND NOT ENABLE_SANDBOX MATCHES "^ON$|^OFF$")
832     message(SEND_ERROR "ENABLE_SANDBOX=${ENABLE_SANDBOX} was used but "
833                         "support for the sandboxing method wasn't found.")
834 endif()
838 # Put the tuklib functions under the lzma_ namespace.
839 target_compile_definitions(liblzma PRIVATE TUKLIB_SYMBOL_PREFIX=lzma_)
840 tuklib_cpucores(liblzma)
841 tuklib_physmem(liblzma)
843 # While liblzma can be built without tuklib_cpucores or tuklib_physmem
844 # modules, the liblzma API functions lzma_cputhreads() and lzma_physmem()
845 # will then be useless (which isn't too bad but still unfortunate). Since
846 # I expect the CMake-based builds to be only used on systems that are
847 # supported by these tuklib modules, problems with these tuklib modules
848 # are considered a hard error for now. This hopefully helps to catch bugs
849 # in the CMake versions of the tuklib checks.
850 if(NOT TUKLIB_CPUCORES_FOUND OR NOT TUKLIB_PHYSMEM_FOUND)
851     # Use SEND_ERROR instead of FATAL_ERROR. If someone reports a bug,
852     # seeing the results of the remaining checks can be useful too.
853     message(SEND_ERROR
854             "tuklib_cpucores() or tuklib_physmem() failed. "
855             "Unless you really are building for a system where these "
856             "modules are not supported (unlikely), this is a bug in the "
857             "included cmake/tuklib_*.cmake files that should be fixed. "
858             "To build anyway, edit this CMakeLists.txt to ignore this error.")
859 endif()
861 # Check for __attribute__((__constructor__)) support.
862 # This needs -Werror because some compilers just warn
863 # about this being unsupported.
864 cmake_push_check_state()
865 set(CMAKE_REQUIRED_FLAGS "-Werror")
866 check_c_source_compiles("
867         __attribute__((__constructor__))
868         static void my_constructor_func(void) { return; }
869         int main(void) { return 0; }
870     "
871     HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
872 cmake_pop_check_state()
873 tuklib_add_definition_if(liblzma HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
875 # The Win95 threading lacks a thread-safe one-time initialization function.
876 # The one-time initialization is needed for crc32_small.c and crc64_small.c
877 # create the CRC tables. So if small mode is enabled, the threading mode is
878 # win95, and the compiler does not support attribute constructor, then we
879 # would end up with a multithreaded build that is thread-unsafe. As a
880 # result this configuration is not allowed.
881 if(USE_WIN95_THREADS AND ENABLE_SMALL AND NOT HAVE_FUNC_ATTRIBUTE_CONSTRUCTOR)
882     message(SEND_ERROR "Threading method win95 and ENABLE_SMALL "
883                         "cannot be used at the same time with a compiler "
884                         "that doesn't support "
885                         "__attribute__((__constructor__))")
886 endif()
889 # Check for __attribute__((__ifunc__())) support.
890 # Supported values for USE_ATTR_IFUNC:
892 # auto (default) - Detect ifunc support with a compile test.
893 # ON             - Always enable ifunc.
894 # OFF            - Disable ifunc usage.
895 set(USE_ATTR_IFUNC "auto" CACHE STRING "Use __attribute__((__ifunc__())).")
897 set(SUPPORTED_USE_ATTR_IFUNC auto ON OFF)
899 if(NOT USE_ATTR_IFUNC IN_LIST SUPPORTED_USE_ATTR_IFUNC)
900     message(FATAL_ERROR "'${USE_ATTR_IFUNC}' is not a supported value for"
901                         "USE_ATTR_IFUNC")
902 endif()
904 # When USE_ATTR_IFUNC is 'auto', allow the use of __attribute__((__ifunc__()))
905 # if compiler support is detected and we are building for GNU/Linux (glibc)
906 # or FreeBSD. uClibc and musl don't support ifunc in their dynamic linkers
907 # but some compilers still accept the attribute when compiling for these
908 # C libraries, which results in broken binaries. That's why we need to
909 # check which libc is being used.
910 if(USE_ATTR_IFUNC STREQUAL "auto")
911     cmake_push_check_state()
912     set(CMAKE_REQUIRED_FLAGS "-Werror")
914     check_c_source_compiles("
915             /*
916              * Force a compilation error when not using glibc on Linux
917              * or if we are not using FreeBSD. uClibc will define
918              * __GLIBC__ but does not support ifunc, so we must have
919              * an extra check to disable with uClibc.
920              */
921             #if defined(__linux__)
922             #   include <features.h>
923             #   if !defined(__GLIBC__) || defined(__UCLIBC__)
924             compile error
925             #   endif
926             #elif !defined(__FreeBSD__)
927             compile error
928             #endif
930             static void func(void) { return; }
931             static void (*resolve_func(void)) (void) { return func; }
932             void func_ifunc(void)
933                     __attribute__((__ifunc__(\"resolve_func\")));
934             int main(void) { return 0; }
935             /*
936              * 'clang -Wall' incorrectly warns that resolve_func is
937              * unused (-Wunused-function). Correct assembly output is
938              * still produced. This problem exists at least in Clang
939              * versions 4 to 17. The following silences the bogus warning:
940              */
941             void make_clang_quiet(void);
942             void make_clang_quiet(void) { resolve_func()(); }
943         "
944         SYSTEM_SUPPORTS_IFUNC)
946         cmake_pop_check_state()
947 endif()
949 if(USE_ATTR_IFUNC STREQUAL "ON" OR SYSTEM_SUPPORTS_IFUNC)
950     tuklib_add_definitions(liblzma HAVE_FUNC_ATTRIBUTE_IFUNC)
952     if(CMAKE_C_FLAGS MATCHES "-fsanitize=")
953         message(SEND_ERROR
954                 "CMAKE_C_FLAGS or the environment variable CFLAGS "
955                 "contains '-fsanitize=' which is incompatible "
956                 "with ifunc. Use -DUSE_ATTR_IFUNC=OFF "
957                 "as an argument to 'cmake' when using '-fsanitize'.")
958     endif()
959 endif()
961 # cpuid.h
962 check_include_file(cpuid.h HAVE_CPUID_H)
963 tuklib_add_definition_if(liblzma HAVE_CPUID_H)
965 # immintrin.h:
966 check_include_file(immintrin.h HAVE_IMMINTRIN_H)
967 if(HAVE_IMMINTRIN_H)
968     target_compile_definitions(liblzma PRIVATE HAVE_IMMINTRIN_H)
970     # SSE2 intrinsics:
971     check_c_source_compiles("
972             #include <immintrin.h>
973             int main(void)
974             {
975                 __m128i x = { 0 };
976                 _mm_movemask_epi8(x);
977                 return 0;
978             }
979         "
980         HAVE__MM_MOVEMASK_EPI8)
981     tuklib_add_definition_if(liblzma HAVE__MM_MOVEMASK_EPI8)
983     # CLMUL intrinsic:
984     option(ALLOW_CLMUL_CRC "Allow carryless multiplication for CRC \
985 calculation if supported by the system" ON)
987     if(ALLOW_CLMUL_CRC)
988         check_c_source_compiles("
989                 #include <immintrin.h>
990                 #if defined(__e2k__) && __iset__ < 6
991                 #   error
992                 #endif
993                 #if (defined(__GNUC__) || defined(__clang__)) \
994                         && !defined(__EDG__)
995                 __attribute__((__target__(\"ssse3,sse4.1,pclmul\")))
996                 #endif
997                 __m128i my_clmul(__m128i a)
998                 {
999                     const __m128i b = _mm_set_epi64x(1, 2);
1000                     return _mm_clmulepi64_si128(a, b, 0);
1001                 }
1002                 int main(void) { return 0; }
1003             "
1004             HAVE_USABLE_CLMUL)
1005         tuklib_add_definition_if(liblzma HAVE_USABLE_CLMUL)
1006     endif()
1007 endif()
1009 # Support -fvisiblity=hidden when building shared liblzma.
1010 # These lines do nothing on Windows (even under Cygwin).
1011 # HAVE_VISIBILITY should always be defined to 0 or 1.
1012 if(BUILD_SHARED_LIBS)
1013     set_target_properties(liblzma PROPERTIES C_VISIBILITY_PRESET hidden)
1014     target_compile_definitions(liblzma PRIVATE HAVE_VISIBILITY=1)
1015 else()
1016     target_compile_definitions(liblzma PRIVATE HAVE_VISIBILITY=0)
1017 endif()
1019 if(WIN32)
1020     if(BUILD_SHARED_LIBS)
1021         # Add the Windows resource file for liblzma.dll.
1022         target_sources(liblzma PRIVATE src/liblzma/liblzma_w32res.rc)
1024         set_target_properties(liblzma PROPERTIES
1025             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1026         )
1028         # Export the public API symbols with __declspec(dllexport).
1029         target_compile_definitions(liblzma PRIVATE DLL_EXPORT)
1031         if(NOT MSVC)
1032             # Create a DEF file. The linker puts the ordinal numbers there
1033             # too so the output from the linker isn't our final file.
1034             target_link_options(liblzma PRIVATE
1035                                 "-Wl,--output-def,liblzma.def.in")
1037             # Remove the ordinal numbers from the DEF file so that
1038             # no one will create an import library that links by ordinal
1039             # instead of by name. We don't maintain a DEF file so the
1040             # ordinal numbers aren't stable.
1041             add_custom_command(TARGET liblzma POST_BUILD
1042                 COMMAND "${CMAKE_COMMAND}"
1043                     -DINPUT_FILE=liblzma.def.in
1044                     -DOUTPUT_FILE=liblzma.def
1045                     -P
1046                     "${CMAKE_CURRENT_SOURCE_DIR}/cmake/remove-ordinals.cmake"
1047                 BYPRODUCTS "liblzma.def"
1048                 VERBATIM)
1049         endif()
1050     else()
1051         # Disable __declspec(dllimport) when linking against static liblzma.
1052         target_compile_definitions(liblzma INTERFACE LZMA_API_STATIC)
1053     endif()
1054 elseif(BUILD_SHARED_LIBS AND CMAKE_SYSTEM_NAME STREQUAL "Linux")
1055     # GNU/Linux-specific symbol versioning for shared liblzma.
1056     # Note that adding link options doesn't affect static builds
1057     # but HAVE_SYMBOL_VERSIONS_LINUX must not be used with static builds
1058     # because it would put symbol versions into the static library which
1059     # can cause problems. It's clearer if all symver related things are
1060     # omitted when not building a shared library.
1061     #
1062     # NOTE: Set it explicitly to 1 to make it clear that versioning is
1063     # done unconditionally in the C files.
1064     target_compile_definitions(liblzma PRIVATE HAVE_SYMBOL_VERSIONS_LINUX=1)
1065     target_link_options(liblzma PRIVATE
1066         "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_linux.map"
1067     )
1068     set_target_properties(liblzma PROPERTIES
1069         LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_linux.map"
1070     )
1071 elseif(BUILD_SHARED_LIBS AND CMAKE_SYSTEM_NAME STREQUAL "FreeBSD")
1072     # Symbol versioning for shared liblzma for non-GNU/Linux.
1073     # FIXME? What about Solaris?
1074     target_link_options(liblzma PRIVATE
1075         "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_generic.map"
1076     )
1077     set_target_properties(liblzma PROPERTIES
1078         LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_generic.map"
1079     )
1080 endif()
1082 set_target_properties(liblzma PROPERTIES
1083     # At least for now the package versioning matches the rules used for
1084     # shared library versioning (excluding development releases) so it is
1085     # fine to use the package version here.
1086     SOVERSION "${xz_VERSION_MAJOR}"
1087     VERSION "${xz_VERSION}"
1089     # It's liblzma.so or liblzma.dll, not libliblzma.so or lzma.dll.
1090     # Avoid the name lzma.dll because it would conflict with LZMA SDK.
1091     PREFIX ""
1092     IMPORT_PREFIX ""
1095 # Create liblzma-config-version.cmake.
1097 # FIXME: SameMajorVersion is correct for stable releases but it is wrong
1098 # for development releases where each release may have incompatible changes.
1099 include(CMakePackageConfigHelpers)
1100 write_basic_package_version_file(
1101     "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config-version.cmake"
1102     VERSION "${liblzma_VERSION}"
1103     COMPATIBILITY SameMajorVersion)
1105 # Create liblzma-config.cmake. We use this spelling instead of
1106 # liblzmaConfig.cmake to make find_package work in case insensitive
1107 # manner even with case sensitive file systems. This gives more consistent
1108 # behavior between operating systems. This optionally includes a dependency
1109 # on a threading library, so the contents are created in two separate parts.
1110 # The "second half" is always needed, so create it first.
1111 set(LZMA_CONFIG_CONTENTS
1112 "include(\"\${CMAKE_CURRENT_LIST_DIR}/liblzma-targets.cmake\")
1114 if(NOT TARGET LibLZMA::LibLZMA)
1115     # Be compatible with the spelling used by the FindLibLZMA module. This
1116     # doesn't use ALIAS because it would make CMake resolve LibLZMA::LibLZMA
1117     # to liblzma::liblzma instead of keeping the original spelling. Keeping
1118     # the original spelling is important for good FindLibLZMA compatibility.
1119     add_library(LibLZMA::LibLZMA INTERFACE IMPORTED)
1120     set_target_properties(LibLZMA::LibLZMA PROPERTIES
1121                           INTERFACE_LINK_LIBRARIES liblzma::liblzma)
1122 endif()
1125 if(USE_POSIX_THREADS)
1126     set(LZMA_CONFIG_CONTENTS
1127 "include(CMakeFindDependencyMacro)
1128 set(THREADS_PREFER_PTHREAD_FLAG TRUE)
1129 find_dependency(Threads)
1131 ${LZMA_CONFIG_CONTENTS}
1133 endif()
1135 file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config.cmake"
1136         "${LZMA_CONFIG_CONTENTS}")
1138 # Set CMAKE_INSTALL_LIBDIR and friends.
1139 include(GNUInstallDirs)
1141 # Create liblzma.pc.
1142 set(prefix "${CMAKE_INSTALL_PREFIX}")
1143 set(exec_prefix "${CMAKE_INSTALL_PREFIX}")
1144 set(libdir "${CMAKE_INSTALL_FULL_LIBDIR}")
1145 set(includedir "${CMAKE_INSTALL_FULL_INCLUDEDIR}")
1146 set(PTHREAD_CFLAGS "${CMAKE_THREAD_LIBS_INIT}")
1147 configure_file(src/liblzma/liblzma.pc.in liblzma.pc
1148                @ONLY
1149                NEWLINE_STYLE LF)
1151 # Install the library binary. The INCLUDES specifies the include path that
1152 # is exported for other projects to use but it doesn't install any files.
1153 install(TARGETS liblzma EXPORT liblzmaTargets
1154         RUNTIME  DESTINATION "${CMAKE_INSTALL_BINDIR}"
1155                  COMPONENT liblzma_Runtime
1156         LIBRARY  DESTINATION "${CMAKE_INSTALL_LIBDIR}"
1157                  COMPONENT liblzma_Runtime
1158                  NAMELINK_COMPONENT liblzma_Development
1159         ARCHIVE  DESTINATION "${CMAKE_INSTALL_LIBDIR}"
1160                  COMPONENT liblzma_Development
1161         INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
1163 # Install the liblzma API headers. These use a subdirectory so
1164 # this has to be done as a separate step.
1165 install(DIRECTORY src/liblzma/api/
1166         COMPONENT liblzma_Development
1167         DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
1168         FILES_MATCHING PATTERN "*.h")
1170 # Install the CMake files that other packages can use to find liblzma.
1171 set(liblzma_INSTALL_CMAKEDIR
1172     "${CMAKE_INSTALL_LIBDIR}/cmake/liblzma"
1173     CACHE STRING "Path to liblzma's .cmake files")
1175 install(EXPORT liblzmaTargets
1176         NAMESPACE liblzma::
1177         FILE liblzma-targets.cmake
1178         DESTINATION "${liblzma_INSTALL_CMAKEDIR}"
1179         COMPONENT liblzma_Development)
1181 install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config.cmake"
1182               "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config-version.cmake"
1183         DESTINATION "${liblzma_INSTALL_CMAKEDIR}"
1184         COMPONENT liblzma_Development)
1186 if(NOT MSVC)
1187     install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblzma.pc"
1188             DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig"
1189             COMPONENT liblzma_Development)
1190 endif()
1193 #############################################################################
1194 # libgnu (getopt_long)
1195 #############################################################################
1197 # This mirrors how the Autotools build system handles the getopt_long
1198 # replacement, calling the object library libgnu since the replacement
1199 # version comes from Gnulib.
1200 add_library(libgnu OBJECT)
1202 # CMake requires that even an object library must have at least once source
1203 # file. So we give it a header file that results in no output files.
1204 target_sources(libgnu PRIVATE lib/getopt.in.h)
1206 # The Ninja Generator requires setting the linker language since it cannot
1207 # guess the programming language of just a header file. Setting this
1208 # property avoids needing an empty .c file or an non-empty unnecessary .c
1209 # file.
1210 set_target_properties(libgnu PROPERTIES LINKER_LANGUAGE C)
1212 # Create /lib directory in the build directory and add it to the include path.
1213 file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/lib")
1214 target_include_directories(libgnu PUBLIC "${CMAKE_CURRENT_BINARY_DIR}/lib")
1216 # Include /lib from the source directory. It does no harm even if none of
1217 # the Gnulib replacements are used.
1218 target_include_directories(libgnu PUBLIC lib)
1220 # The command line tools need getopt_long in order to parse arguments. If
1221 # the system does not have a getopt_long implementation we can use the one
1222 # from Gnulib instead.
1223 check_symbol_exists(getopt_long getopt.h HAVE_GETOPT_LONG)
1225 if(NOT HAVE_GETOPT_LONG)
1226     # Set the __GETOPT_PREFIX definition to "rpl_" (replacement) to avoid
1227     # name conflicts with libc symbols. The same prefix is set if using
1228     # the Autotools build (m4/getopt.m4).
1229     target_compile_definitions(libgnu PUBLIC "__GETOPT_PREFIX=rpl_")
1231     # Create a custom copy command to copy the getopt header to the build
1232     # directory and re-copy it if it is updated. (Gnulib does it this way
1233     # because it allows choosing which .in.h files to actually use in the
1234     # build. We need just getopt.h so this is a bit overcomplicated for
1235     # a single header file only.)
1236     add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1237         COMMAND "${CMAKE_COMMAND}" -E copy
1238             "${CMAKE_CURRENT_SOURCE_DIR}/lib/getopt.in.h"
1239             "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1240         MAIN_DEPENDENCY "${CMAKE_CURRENT_SOURCE_DIR}/lib/getopt.in.h"
1241         VERBATIM)
1243     target_sources(libgnu PRIVATE
1244         lib/getopt1.c
1245         lib/getopt.c
1246         lib/getopt_int.h
1247         lib/getopt-cdefs.h
1248         lib/getopt-core.h
1249         lib/getopt-ext.h
1250         lib/getopt-pfx-core.h
1251         lib/getopt-pfx-ext.h
1252         "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1253     )
1254 endif()
1257 #############################################################################
1258 # xzdec
1259 #############################################################################
1261 if(HAVE_DECODERS AND (NOT MSVC OR MSVC_VERSION GREATER_EQUAL 1900))
1262     add_executable(xzdec
1263         src/common/sysdefs.h
1264         src/common/tuklib_common.h
1265         src/common/tuklib_config.h
1266         src/common/tuklib_exit.c
1267         src/common/tuklib_exit.h
1268         src/common/tuklib_gettext.h
1269         src/common/tuklib_progname.c
1270         src/common/tuklib_progname.h
1271         src/xzdec/xzdec.c
1272     )
1274     target_include_directories(xzdec PRIVATE
1275         src/common
1276         src/liblzma/api
1277     )
1279     target_link_libraries(xzdec PRIVATE liblzma libgnu)
1281     if(WIN32)
1282         # Add the Windows resource file for xzdec.exe.
1283         target_sources(xzdec PRIVATE src/xzdec/xzdec_w32res.rc)
1284         set_target_properties(xzdec PROPERTIES
1285             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1286         )
1287     endif()
1289     if(SANDBOX_COMPILE_DEFINITION)
1290         target_compile_definitions(xzdec PRIVATE
1291                                    "${SANDBOX_COMPILE_DEFINITION}")
1292     endif()
1294     tuklib_progname(xzdec)
1296     install(TARGETS xzdec
1297             RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1298                     COMPONENT xzdec)
1300     if(UNIX)
1301         install(FILES src/xzdec/xzdec.1
1302                 DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
1303                 COMPONENT xzdec)
1304     endif()
1305 endif()
1308 #############################################################################
1309 # xz
1310 #############################################################################
1312 if(NOT MSVC OR MSVC_VERSION GREATER_EQUAL 1900)
1313     add_executable(xz
1314         src/common/mythread.h
1315         src/common/sysdefs.h
1316         src/common/tuklib_common.h
1317         src/common/tuklib_config.h
1318         src/common/tuklib_exit.c
1319         src/common/tuklib_exit.h
1320         src/common/tuklib_gettext.h
1321         src/common/tuklib_integer.h
1322         src/common/tuklib_mbstr.h
1323         src/common/tuklib_mbstr_fw.c
1324         src/common/tuklib_mbstr_width.c
1325         src/common/tuklib_open_stdxxx.c
1326         src/common/tuklib_open_stdxxx.h
1327         src/common/tuklib_progname.c
1328         src/common/tuklib_progname.h
1329         src/xz/args.c
1330         src/xz/args.h
1331         src/xz/coder.c
1332         src/xz/coder.h
1333         src/xz/file_io.c
1334         src/xz/file_io.h
1335         src/xz/hardware.c
1336         src/xz/hardware.h
1337         src/xz/main.c
1338         src/xz/main.h
1339         src/xz/message.c
1340         src/xz/message.h
1341         src/xz/mytime.c
1342         src/xz/mytime.h
1343         src/xz/options.c
1344         src/xz/options.h
1345         src/xz/private.h
1346         src/xz/signals.c
1347         src/xz/signals.h
1348         src/xz/suffix.c
1349         src/xz/suffix.h
1350         src/xz/util.c
1351         src/xz/util.h
1352     )
1354     target_include_directories(xz PRIVATE
1355         src/common
1356         src/liblzma/api
1357     )
1359     if(HAVE_DECODERS)
1360         target_sources(xz PRIVATE
1361             src/xz/list.c
1362             src/xz/list.h
1363         )
1364     endif()
1366     target_link_libraries(xz PRIVATE liblzma libgnu)
1368     target_compile_definitions(xz PRIVATE ASSUME_RAM=128)
1370     if(WIN32)
1371         # Add the Windows resource file for xz.exe.
1372         target_sources(xz PRIVATE src/xz/xz_w32res.rc)
1373         set_target_properties(xz PROPERTIES
1374             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1375         )
1376     endif()
1378     if(SANDBOX_COMPILE_DEFINITION)
1379         target_compile_definitions(xz PRIVATE "${SANDBOX_COMPILE_DEFINITION}")
1380     endif()
1382     tuklib_progname(xz)
1383     tuklib_mbstr(xz)
1385     check_symbol_exists(optreset getopt.h HAVE_OPTRESET)
1386     tuklib_add_definition_if(xz HAVE_OPTRESET)
1388     check_symbol_exists(posix_fadvise fcntl.h HAVE_POSIX_FADVISE)
1389     tuklib_add_definition_if(xz HAVE_POSIX_FADVISE)
1391     # How to get file time:
1392     check_struct_has_member("struct stat" st_atim.tv_nsec
1393                             "sys/types.h;sys/stat.h"
1394                             HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1395     if(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1396         tuklib_add_definitions(xz HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1397     else()
1398         check_struct_has_member("struct stat" st_atimespec.tv_nsec
1399                                 "sys/types.h;sys/stat.h"
1400                                 HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1401         if(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1402             tuklib_add_definitions(xz HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1403         else()
1404             check_struct_has_member("struct stat" st_atimensec
1405                                     "sys/types.h;sys/stat.h"
1406                                     HAVE_STRUCT_STAT_ST_ATIMENSEC)
1407             tuklib_add_definition_if(xz HAVE_STRUCT_STAT_ST_ATIMENSEC)
1408         endif()
1409     endif()
1411     # How to set file time:
1412     check_symbol_exists(futimens "sys/types.h;sys/stat.h" HAVE_FUTIMENS)
1413     if(HAVE_FUTIMENS)
1414         tuklib_add_definitions(xz HAVE_FUTIMENS)
1415     else()
1416         check_symbol_exists(futimes "sys/time.h" HAVE_FUTIMES)
1417         if(HAVE_FUTIMES)
1418             tuklib_add_definitions(xz HAVE_FUTIMES)
1419         else()
1420             check_symbol_exists(futimesat "sys/time.h" HAVE_FUTIMESAT)
1421             if(HAVE_FUTIMESAT)
1422                 tuklib_add_definitions(xz HAVE_FUTIMESAT)
1423             else()
1424                 check_symbol_exists(utimes "sys/time.h" HAVE_UTIMES)
1425                 if(HAVE_UTIMES)
1426                     tuklib_add_definitions(xz HAVE_UTIMES)
1427                 else()
1428                     check_symbol_exists(_futime "sys/utime.h" HAVE__FUTIME)
1429                     if(HAVE__FUTIME)
1430                         tuklib_add_definitions(xz HAVE__FUTIME)
1431                     else()
1432                         check_symbol_exists(utime "utime.h" HAVE_UTIME)
1433                         tuklib_add_definition_if(xz HAVE_UTIME)
1434                     endif()
1435                 endif()
1436             endif()
1437         endif()
1438     endif()
1440     install(TARGETS xz
1441             RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1442                     COMPONENT xz)
1444     if(UNIX)
1445         install(FILES src/xz/xz.1
1446                 DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
1447                 COMPONENT xz)
1449         option(CREATE_XZ_SYMLINKS "Create unxz and xzcat symlinks" ON)
1450         option(CREATE_LZMA_SYMLINKS "Create lzma, unlzma, and lzcat symlinks"
1451                ON)
1452         set(XZ_LINKS)
1454         if(CREATE_XZ_SYMLINKS)
1455             list(APPEND XZ_LINKS "unxz" "xzcat")
1456         endif()
1458         if(CREATE_LZMA_SYMLINKS)
1459             list(APPEND XZ_LINKS "lzma" "unlzma" "lzcat")
1460         endif()
1462         # With Windows Cygwin and MSYS2 the symlinking is complicated. Both
1463         # of these environments set the UNIX variable so they will try to
1464         # make the symlinks. The ability for Cygwin and MSYS2 to make
1465         # broken symlinks is determined by the CYGWIN and MSYS2 environment
1466         # variables, respectively. Broken symlinks are needed for the man
1467         # page symlinks and for determining if the xz and lzma symlinks need
1468         # to depend on the xz target or not. If broken symlinks cannot be
1469         # made then the xz binary must be created before the symlinks.
1470         set(ALLOW_BROKEN_SYMLINKS ON)
1472         if(CMAKE_SYSTEM_NAME STREQUAL "CYGWIN")
1473             # The Cygwin env variable can be set to four possible values:
1474             #
1475             # 1. "lnk". Create symlinks as Windows shortcuts.
1476             #
1477             # 2. "native". Create symlinks as native Windows symlinks
1478             #    if supported by the system. Fallback to "lnk" if native
1479             #    symlinks are not supported.
1480             #
1481             # 3. "nativestrict". Create symlinks as native Windows symlinks
1482             #    if supported by the system. If the target of the symlink
1483             #    does not exist or the creation of the symlink fails for any
1484             #    reason, do not create the symlink.
1485             #
1486             # 4. "sys". Create symlinks as plain files with a special
1487             #    system attribute containing the path to the symlink target.
1488             #
1489             # So, the only case we care about for broken symlinks is
1490             # "nativestrict" since all other values mean that broken
1491             # symlinks are allowed. If the env variable is not set the
1492             # default is "native". If the env variable is set but not
1493             # assigned one of the four values, then the default is the same
1494             # as option 1 "lnk".
1495             string(FIND "$ENV{CYGWIN}" "winsymlinks:nativestrict" SYMLINK_POS)
1496             if(SYMLINK_POS GREATER -1)
1497                 set(ALLOW_BROKEN_SYMLINKS OFF)
1498             endif()
1499         elseif(CMAKE_SYSTEM_NAME STREQUAL "MSYS")
1500             # The MSYS env variable behaves similar to the CYGWIN but has a
1501             # different default behavior. If winsymlinks is set but not
1502             # assigned one of the four supported values, the default is to
1503             # *copy* the target to the symlink destination. This will fail
1504             # if the target does not exist so broken symlinks cannot be
1505             # allowed.
1506             string(FIND "$ENV{MSYS}" "winsymlinks" SYMLINK_POS)
1507             if(SYMLINK_POS GREATER -1)
1508                 string(FIND "$ENV{MSYS}" "winsymlinks:nativestrict"
1509                         SYMLINK_POS)
1510                 if(SYMLINK_POS GREATER -1)
1511                     set(ALLOW_BROKEN_SYMLINKS OFF)
1512                 endif()
1513             else()
1514                 set(ALLOW_BROKEN_SYMLINKS OFF)
1515             endif()
1516         endif()
1518         # Create symlinks in the build directory and then install them.
1519         #
1520         # The symlinks do not likely need any special extension since
1521         # even on Windows the symlink can still be executed without
1522         # the .exe extension.
1523         foreach(LINK IN LISTS XZ_LINKS)
1524             add_custom_target("create_${LINK}" ALL
1525                 "${CMAKE_COMMAND}" -E create_symlink
1526                     "$<TARGET_FILE_NAME:xz>" "${LINK}"
1527                 BYPRODUCTS "${LINK}"
1528                 VERBATIM)
1529             install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${LINK}"
1530                     DESTINATION "${CMAKE_INSTALL_BINDIR}"
1531                     COMPONENT xz)
1533             # Only create the man page symlinks if the symlinks can be
1534             # created broken. The symlinks will not be valid until install
1535             # so they cannot be created on these system environments.
1536             if(ALLOW_BROKEN_SYMLINKS)
1537                 add_custom_target("create_${LINK}.1" ALL
1538                     "${CMAKE_COMMAND}" -E create_symlink "xz.1" "${LINK}.1"
1539                     BYPRODUCTS "${LINK}.1"
1540                     VERBATIM)
1541                 install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${LINK}.1"
1542                         DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
1543                         COMPONENT xz)
1544             else()
1545                 # Add the xz target as dependency when broken symlinks
1546                 # cannot be made. This ensures parallel builds do not fail
1547                 # since it will enforce the order of creating xz first, then
1548                 # the symlinks.
1549                 add_dependencies("create_${LINK}" xz)
1550             endif()
1551         endforeach()
1552     endif()
1553 endif()
1556 #############################################################################
1557 # Tests
1558 #############################################################################
1560 include(CTest)
1562 if(BUILD_TESTING)
1563     set(LIBLZMA_TESTS
1564         test_bcj_exact_size
1565         test_block_header
1566         test_check
1567         test_filter_flags
1568         test_filter_str
1569         test_hardware
1570         test_index
1571         test_index_hash
1572         test_lzip_decoder
1573         test_memlimit
1574         test_stream_flags
1575         test_vli
1576     )
1578     foreach(TEST IN LISTS LIBLZMA_TESTS)
1579         add_executable("${TEST}" "tests/${TEST}.c")
1581         target_include_directories("${TEST}" PRIVATE
1582             src/common
1583             src/liblzma/api
1584             src/liblzma
1585         )
1587         target_link_libraries("${TEST}" PRIVATE liblzma)
1589         # Put the test programs into their own subdirectory so they don't
1590         # pollute the top-level dir which might contain xz and xzdec.
1591         set_target_properties("${TEST}" PROPERTIES
1592             RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/tests_bin"
1593         )
1595         add_test(NAME "${TEST}"
1596                  COMMAND "${CMAKE_CURRENT_BINARY_DIR}/tests_bin/${TEST}"
1597         )
1599         # Set srcdir environment variable so that the tests find their
1600         # input files from the source tree.
1601         #
1602         # Set the return code for skipped tests to match Automake convention.
1603         set_tests_properties("${TEST}" PROPERTIES
1604             ENVIRONMENT "srcdir=${CMAKE_CURRENT_SOURCE_DIR}/tests"
1605             SKIP_RETURN_CODE 77
1606         )
1607     endforeach()
1608 endif()