liblzma: Creates Non-resumable and Resumable modes for lzma_decoder.
[xz.git] / CMakeLists.txt
blobf30a82b66189e8b087cec60d9f1c597480df980c
1 # SPDX-License-Identifier: 0BSD
3 #############################################################################
5 # Very limited CMake support for building some parts of XZ Utils
7 # For now, this is intended to be useful to build static or shared liblzma
8 # on Windows with MSVC (to avoid the need to maintain Visual Studio project
9 # files). Building liblzma on a few other platforms should work too but it
10 # is somewhat experimental and not as portable as using ./configure.
12 # On some platforms this builds also xz and xzdec, but these are
13 # highly experimental and meant for testing only:
14 #   - No translations
16 # Other missing things:
17 #   - No xzgrep or other scripts or their symlinks
18 #   - No xz tests (liblzma tests only)
20 # NOTE: Even if the code compiles without warnings, the end result may be
21 # different than via ./configure. Specifically, the list of #defines
22 # may be different (if so, probably this CMakeLists.txt got them wrong).
24 # This file provides the following installation components (if you only
25 # need liblzma, install only its components!):
26 #   - liblzma_Runtime
27 #   - liblzma_Development
28 #   - xz (on some platforms only)
29 #   - xzdec (on some platforms only)
31 # To find the target liblzma::liblzma from other packages, use the CONFIG
32 # option with find_package() to avoid a conflict with the FindLibLZMA module
33 # with case-insensitive file systems. For example, to require liblzma 5.2.5
34 # or a newer compatible version:
36 #     find_package(liblzma 5.2.5 REQUIRED CONFIG)
37 #     target_link_libraries(my_application liblzma::liblzma)
39 #############################################################################
41 # Author: Lasse Collin
43 #############################################################################
45 cmake_minimum_required(VERSION 3.13...3.27 FATAL_ERROR)
47 include(CMakePushCheckState)
48 include(CheckIncludeFile)
49 include(CheckSymbolExists)
50 include(CheckStructHasMember)
51 include(CheckCSourceCompiles)
52 include(cmake/tuklib_large_file_support.cmake)
53 include(cmake/tuklib_integer.cmake)
54 include(cmake/tuklib_cpucores.cmake)
55 include(cmake/tuklib_physmem.cmake)
56 include(cmake/tuklib_progname.cmake)
57 include(cmake/tuklib_mbstr.cmake)
59 set(PACKAGE_NAME "XZ Utils")
60 set(PACKAGE_BUGREPORT "xz@tukaani.org")
61 set(PACKAGE_URL "https://xz.tukaani.org/xz-utils/")
63 # Get the package version from version.h into PACKAGE_VERSION variable.
64 file(READ src/liblzma/api/lzma/version.h PACKAGE_VERSION)
65 string(REGEX REPLACE
66 "^.*\n\
67 #define LZMA_VERSION_MAJOR ([0-9]+)\n\
68 .*\
69 #define LZMA_VERSION_MINOR ([0-9]+)\n\
70 .*\
71 #define LZMA_VERSION_PATCH ([0-9]+)\n\
72 .*$"
73        "\\1.\\2.\\3" PACKAGE_VERSION "${PACKAGE_VERSION}")
75 # Among other things, this gives us variables xz_VERSION and xz_VERSION_MAJOR.
76 project(xz VERSION "${PACKAGE_VERSION}" LANGUAGES C)
78 # We need a compiler that supports enough C99 or newer (variable-length arrays
79 # aren't needed, those are optional in C17). Setting CMAKE_C_STANDARD here
80 # makes it the default for all targets. It doesn't affect the INTERFACE so
81 # liblzma::liblzma won't end up with INTERFACE_COMPILE_FEATURES "c_std_99"
82 # (the API headers are C89 and C++ compatible).
83 set(CMAKE_C_STANDARD 99)
84 set(CMAKE_C_STANDARD_REQUIRED ON)
86 # On Apple OSes, don't build executables as bundles:
87 set(CMAKE_MACOSX_BUNDLE OFF)
89 # windres from GNU binutils can be tricky with command line arguments
90 # that contain spaces or other funny characters. Unfortunately we need
91 # a space in PACKAGE_NAME. Using \x20 to encode the US-ASCII space seems
92 # to work in both cmd.exe and /bin/sh.
94 # However, even \x20 isn't enough in all situations, resulting in
95 # "syntax error" from windres. Using --use-temp-file prevents windres
96 # from using popen() and this seems to fix the problem.
98 # llvm-windres from Clang/LLVM 16.0.6 and older: The \x20 results
99 # in "XZx20Utils" in the compiled binary. The option --use-temp-file
100 # makes no difference.
102 # llvm-windres 17.0.0 and later: It emulates GNU windres more accurately, so
103 # the workarounds used with GNU windres must be used with llvm-windres too.
105 # CMake 3.27 doesn't have CMAKE_RC_COMPILER_ID so we rely on
106 # CMAKE_C_COMPILER_ID.
107 if((MINGW OR CYGWIN OR MSYS) AND (
108         NOT CMAKE_C_COMPILER_ID STREQUAL "Clang" OR
109         CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL "17"))
110     # Use workarounds with GNU windres and llvm-windres >= 17.0.0. The \x20
111     # in PACKAGE_NAME_DEFINITION works with gcc and clang too so we don't need
112     # to worry how to pass different flags to windres and the C compiler.
113     # Keep the original PACKAGE_NAME intact for generation of liblzma.pc.
114     string(APPEND CMAKE_RC_FLAGS " --use-temp-file")
115     string(REPLACE " " "\\x20" PACKAGE_NAME_DEFINITION "${PACKAGE_NAME}")
116 else()
117     # Elsewhere a space is safe. This also keeps things compatible with
118     # EBCDIC in case CMake-based build is ever done on such a system.
119     set(PACKAGE_NAME_DEFINITION "${PACKAGE_NAME}")
120 endif()
122 # Definitions common to all targets:
123 add_compile_definitions(
124     # Package info:
125     PACKAGE_NAME="${PACKAGE_NAME_DEFINITION}"
126     PACKAGE_BUGREPORT="${PACKAGE_BUGREPORT}"
127     PACKAGE_URL="${PACKAGE_URL}"
129     # Standard headers and types are available:
130     HAVE_STDBOOL_H
131     HAVE__BOOL
132     HAVE_STDINT_H
133     HAVE_INTTYPES_H
135     # Always enable CRC32 since liblzma should never build without it.
136     HAVE_CHECK_CRC32
138     # Disable assert() checks when no build type has been specified. Non-empty
139     # build types like "Release" and "Debug" handle this by default.
140     $<$<CONFIG:>:NDEBUG>
144 ######################
145 # System definitions #
146 ######################
148 # _GNU_SOURCE and such definitions. This specific macro is special since
149 # it also adds the definitions to CMAKE_REQUIRED_DEFINITIONS.
150 tuklib_use_system_extensions(ALL)
152 # Check for large file support. It's required on some 32-bit platforms and
153 # even on 64-bit MinGW-w64 to get 64-bit off_t. This can be forced off on
154 # the CMake command line if needed: -DLARGE_FILE_SUPPORT=OFF
155 tuklib_large_file_support(ALL)
157 # This is needed by liblzma and xz.
158 tuklib_integer(ALL)
160 # This is used for liblzma.pc generation to add -lrt if needed.
161 set(LIBS)
163 # Check for clock_gettime(). Do this before checking for threading so
164 # that we know there if CLOCK_MONOTONIC is available.
165 check_symbol_exists(clock_gettime time.h HAVE_CLOCK_GETTIME)
167 if(NOT HAVE_CLOCK_GETTIME)
168     # With glibc <= 2.17 or Solaris 10 this needs librt.
169     # Add librt for the next check for HAVE_CLOCK_GETTIME. If it is
170     # found after including the library, we know that librt is required.
171     list(INSERT CMAKE_REQUIRED_LIBRARIES 0 rt)
172     check_symbol_exists(clock_gettime time.h HAVE_CLOCK_GETTIME_LIBRT)
174     # If it was found now, add librt to all targets and keep it in
175     # CMAKE_REQUIRED_LIBRARIES for further tests too.
176     if(HAVE_CLOCK_GETTIME_LIBRT)
177         link_libraries(rt)
178         set(LIBS "-lrt") # For liblzma.pc
179     else()
180         list(REMOVE_AT CMAKE_REQUIRED_LIBRARIES 0)
181     endif()
182 endif()
184 if(HAVE_CLOCK_GETTIME OR HAVE_CLOCK_GETTIME_LIBRT)
185     add_compile_definitions(HAVE_CLOCK_GETTIME)
187     # Check if CLOCK_MONOTONIC is available for clock_gettime().
188     check_symbol_exists(CLOCK_MONOTONIC time.h HAVE_CLOCK_MONOTONIC)
189     tuklib_add_definition_if(ALL HAVE_CLOCK_MONOTONIC)
190 endif()
192 # Options for new enough GCC or Clang on any arch or operating system:
193 if(CMAKE_C_COMPILER_ID MATCHES GNU|Clang)
194     # configure.ac has a long list but it won't be copied here:
195     add_compile_options(-Wall -Wextra)
196 endif()
199 #############################################################################
200 # liblzma
201 #############################################################################
203 option(BUILD_SHARED_LIBS "Build liblzma as a shared library instead of static")
205 add_library(liblzma
206     src/common/mythread.h
207     src/common/sysdefs.h
208     src/common/tuklib_common.h
209     src/common/tuklib_config.h
210     src/common/tuklib_integer.h
211     src/common/tuklib_physmem.c
212     src/common/tuklib_physmem.h
213     src/liblzma/api/lzma.h
214     src/liblzma/api/lzma/base.h
215     src/liblzma/api/lzma/bcj.h
216     src/liblzma/api/lzma/block.h
217     src/liblzma/api/lzma/check.h
218     src/liblzma/api/lzma/container.h
219     src/liblzma/api/lzma/delta.h
220     src/liblzma/api/lzma/filter.h
221     src/liblzma/api/lzma/hardware.h
222     src/liblzma/api/lzma/index.h
223     src/liblzma/api/lzma/index_hash.h
224     src/liblzma/api/lzma/lzma12.h
225     src/liblzma/api/lzma/stream_flags.h
226     src/liblzma/api/lzma/version.h
227     src/liblzma/api/lzma/vli.h
228     src/liblzma/check/check.c
229     src/liblzma/check/check.h
230     src/liblzma/check/crc_common.h
231     src/liblzma/check/crc_x86_clmul.h
232     src/liblzma/check/crc32_arm64.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 # ARM64 C Language Extensions define CRC32 functions in arm_acle.h.
1010 # These are supported by at least GCC and Clang which both need
1011 # __attribute__((__target__("+crc"))), unless the needed compiler flags
1012 # are used to support the CRC instruction.
1013 option(ALLOW_ARM64_CRC32 "Allow ARM64 CRC32 instruction if supported by \
1014 the system" ON)
1016 if(ALLOW_ARM64_CRC32)
1017     check_c_source_compiles("
1018             #include <stdint.h>
1020             #ifndef _MSC_VER
1021             #include <arm_acle.h>
1022             #endif
1024             #if (defined(__GNUC__) || defined(__clang__)) && !defined(__EDG__)
1025             __attribute__((__target__(\"+crc\")))
1026             #endif
1027             uint32_t my_crc(uint32_t a, uint64_t b)
1028             {
1029                 return __crc32d(a, b);
1030             }
1031             int main(void) { return 0; }
1032         "
1033         HAVE_ARM64_CRC32)
1035     if(HAVE_ARM64_CRC32)
1036         target_compile_definitions(liblzma PRIVATE HAVE_ARM64_CRC32)
1038         # Check for ARM64 CRC32 instruction runtime detection.
1039         # getauxval() is supported on Linux.
1040         check_symbol_exists(getauxval sys/auxv.h HAVE_GETAUXVAL)
1041         tuklib_add_definition_if(liblzma HAVE_GETAUXVAL)
1043         # elf_aux_info() is supported on FreeBSD.
1044         check_symbol_exists(elf_aux_info sys/auxv.h HAVE_ELF_AUX_INFO)
1045         tuklib_add_definition_if(liblzma HAVE_ELF_AUX_INFO)
1047         # sysctlbyname("hw.optional.armv8_crc32", ...) is supported on Darwin
1048         # (macOS, iOS, etc.). Note that sysctlbyname() is supported on FreeBSD,
1049         # NetBSD, and possibly others too but the string is specific to
1050         # Apple OSes. The C code is responsible for checking
1051         # defined(__APPLE__) before using
1052         # sysctlbyname("hw.optional.armv8_crc32", ...).
1053         check_symbol_exists(sysctlbyname sys/sysctl.h HAVE_SYSCTLBYNAME)
1054         tuklib_add_definition_if(liblzma HAVE_SYSCTLBYNAME)
1055     endif()
1056 endif()
1059 # Support -fvisiblity=hidden when building shared liblzma.
1060 # These lines do nothing on Windows (even under Cygwin).
1061 # HAVE_VISIBILITY should always be defined to 0 or 1.
1062 if(BUILD_SHARED_LIBS)
1063     set_target_properties(liblzma PROPERTIES C_VISIBILITY_PRESET hidden)
1064     target_compile_definitions(liblzma PRIVATE HAVE_VISIBILITY=1)
1065 else()
1066     target_compile_definitions(liblzma PRIVATE HAVE_VISIBILITY=0)
1067 endif()
1069 if(WIN32)
1070     if(BUILD_SHARED_LIBS)
1071         # Add the Windows resource file for liblzma.dll.
1072         target_sources(liblzma PRIVATE src/liblzma/liblzma_w32res.rc)
1074         set_target_properties(liblzma PROPERTIES
1075             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1076         )
1078         # Export the public API symbols with __declspec(dllexport).
1079         target_compile_definitions(liblzma PRIVATE DLL_EXPORT)
1081         if(NOT MSVC)
1082             # Create a DEF file. The linker puts the ordinal numbers there
1083             # too so the output from the linker isn't our final file.
1084             target_link_options(liblzma PRIVATE
1085                                 "-Wl,--output-def,liblzma.def.in")
1087             # Remove the ordinal numbers from the DEF file so that
1088             # no one will create an import library that links by ordinal
1089             # instead of by name. We don't maintain a DEF file so the
1090             # ordinal numbers aren't stable.
1091             add_custom_command(TARGET liblzma POST_BUILD
1092                 COMMAND "${CMAKE_COMMAND}"
1093                     -DINPUT_FILE=liblzma.def.in
1094                     -DOUTPUT_FILE=liblzma.def
1095                     -P
1096                     "${CMAKE_CURRENT_SOURCE_DIR}/cmake/remove-ordinals.cmake"
1097                 BYPRODUCTS "liblzma.def"
1098                 VERBATIM)
1099         endif()
1100     else()
1101         # Disable __declspec(dllimport) when linking against static liblzma.
1102         target_compile_definitions(liblzma INTERFACE LZMA_API_STATIC)
1103     endif()
1104 elseif(BUILD_SHARED_LIBS AND CMAKE_SYSTEM_NAME STREQUAL "Linux")
1105     # GNU/Linux-specific symbol versioning for shared liblzma.
1106     # Note that adding link options doesn't affect static builds
1107     # but HAVE_SYMBOL_VERSIONS_LINUX must not be used with static builds
1108     # because it would put symbol versions into the static library which
1109     # can cause problems. It's clearer if all symver related things are
1110     # omitted when not building a shared library.
1111     #
1112     # NOTE: Set it explicitly to 1 to make it clear that versioning is
1113     # done unconditionally in the C files.
1114     target_compile_definitions(liblzma PRIVATE HAVE_SYMBOL_VERSIONS_LINUX=1)
1115     target_link_options(liblzma PRIVATE
1116         "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_linux.map"
1117     )
1118     set_target_properties(liblzma PROPERTIES
1119         LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_linux.map"
1120     )
1121 elseif(BUILD_SHARED_LIBS AND CMAKE_SYSTEM_NAME STREQUAL "FreeBSD")
1122     # Symbol versioning for shared liblzma for non-GNU/Linux.
1123     # FIXME? What about Solaris?
1124     target_link_options(liblzma PRIVATE
1125         "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_generic.map"
1126     )
1127     set_target_properties(liblzma PROPERTIES
1128         LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/liblzma/liblzma_generic.map"
1129     )
1130 endif()
1132 set_target_properties(liblzma PROPERTIES
1133     # At least for now the package versioning matches the rules used for
1134     # shared library versioning (excluding development releases) so it is
1135     # fine to use the package version here.
1136     SOVERSION "${xz_VERSION_MAJOR}"
1137     VERSION "${xz_VERSION}"
1139     # It's liblzma.so or liblzma.dll, not libliblzma.so or lzma.dll.
1140     # Avoid the name lzma.dll because it would conflict with LZMA SDK.
1141     PREFIX ""
1142     IMPORT_PREFIX ""
1145 # Create liblzma-config-version.cmake.
1147 # FIXME: SameMajorVersion is correct for stable releases but it is wrong
1148 # for development releases where each release may have incompatible changes.
1149 include(CMakePackageConfigHelpers)
1150 write_basic_package_version_file(
1151     "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config-version.cmake"
1152     VERSION "${liblzma_VERSION}"
1153     COMPATIBILITY SameMajorVersion)
1155 # Create liblzma-config.cmake. We use this spelling instead of
1156 # liblzmaConfig.cmake to make find_package work in case insensitive
1157 # manner even with case sensitive file systems. This gives more consistent
1158 # behavior between operating systems. This optionally includes a dependency
1159 # on a threading library, so the contents are created in two separate parts.
1160 # The "second half" is always needed, so create it first.
1161 set(LZMA_CONFIG_CONTENTS
1162 "include(\"\${CMAKE_CURRENT_LIST_DIR}/liblzma-targets.cmake\")
1164 if(NOT TARGET LibLZMA::LibLZMA)
1165     # Be compatible with the spelling used by the FindLibLZMA module. This
1166     # doesn't use ALIAS because it would make CMake resolve LibLZMA::LibLZMA
1167     # to liblzma::liblzma instead of keeping the original spelling. Keeping
1168     # the original spelling is important for good FindLibLZMA compatibility.
1169     add_library(LibLZMA::LibLZMA INTERFACE IMPORTED)
1170     set_target_properties(LibLZMA::LibLZMA PROPERTIES
1171                           INTERFACE_LINK_LIBRARIES liblzma::liblzma)
1172 endif()
1175 if(USE_POSIX_THREADS)
1176     set(LZMA_CONFIG_CONTENTS
1177 "include(CMakeFindDependencyMacro)
1178 set(THREADS_PREFER_PTHREAD_FLAG TRUE)
1179 find_dependency(Threads)
1181 ${LZMA_CONFIG_CONTENTS}
1183 endif()
1185 file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config.cmake"
1186         "${LZMA_CONFIG_CONTENTS}")
1188 # Set CMAKE_INSTALL_LIBDIR and friends.
1189 include(GNUInstallDirs)
1191 # Create liblzma.pc.
1192 set(prefix "${CMAKE_INSTALL_PREFIX}")
1193 set(exec_prefix "${CMAKE_INSTALL_PREFIX}")
1194 set(libdir "${CMAKE_INSTALL_FULL_LIBDIR}")
1195 set(includedir "${CMAKE_INSTALL_FULL_INCLUDEDIR}")
1196 set(PTHREAD_CFLAGS "${CMAKE_THREAD_LIBS_INIT}")
1197 configure_file(src/liblzma/liblzma.pc.in liblzma.pc
1198                @ONLY
1199                NEWLINE_STYLE LF)
1201 # Install the library binary. The INCLUDES specifies the include path that
1202 # is exported for other projects to use but it doesn't install any files.
1203 install(TARGETS liblzma EXPORT liblzmaTargets
1204         RUNTIME  DESTINATION "${CMAKE_INSTALL_BINDIR}"
1205                  COMPONENT liblzma_Runtime
1206         LIBRARY  DESTINATION "${CMAKE_INSTALL_LIBDIR}"
1207                  COMPONENT liblzma_Runtime
1208                  NAMELINK_COMPONENT liblzma_Development
1209         ARCHIVE  DESTINATION "${CMAKE_INSTALL_LIBDIR}"
1210                  COMPONENT liblzma_Development
1211         INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
1213 # Install the liblzma API headers. These use a subdirectory so
1214 # this has to be done as a separate step.
1215 install(DIRECTORY src/liblzma/api/
1216         COMPONENT liblzma_Development
1217         DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
1218         FILES_MATCHING PATTERN "*.h")
1220 # Install the CMake files that other packages can use to find liblzma.
1221 set(liblzma_INSTALL_CMAKEDIR
1222     "${CMAKE_INSTALL_LIBDIR}/cmake/liblzma"
1223     CACHE STRING "Path to liblzma's .cmake files")
1225 install(EXPORT liblzmaTargets
1226         NAMESPACE liblzma::
1227         FILE liblzma-targets.cmake
1228         DESTINATION "${liblzma_INSTALL_CMAKEDIR}"
1229         COMPONENT liblzma_Development)
1231 install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config.cmake"
1232               "${CMAKE_CURRENT_BINARY_DIR}/liblzma-config-version.cmake"
1233         DESTINATION "${liblzma_INSTALL_CMAKEDIR}"
1234         COMPONENT liblzma_Development)
1236 if(NOT MSVC)
1237     install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblzma.pc"
1238             DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig"
1239             COMPONENT liblzma_Development)
1240 endif()
1243 #############################################################################
1244 # libgnu (getopt_long)
1245 #############################################################################
1247 # This mirrors how the Autotools build system handles the getopt_long
1248 # replacement, calling the object library libgnu since the replacement
1249 # version comes from Gnulib.
1250 add_library(libgnu OBJECT)
1252 # CMake requires that even an object library must have at least once source
1253 # file. So we give it a header file that results in no output files.
1254 target_sources(libgnu PRIVATE lib/getopt.in.h)
1256 # The Ninja Generator requires setting the linker language since it cannot
1257 # guess the programming language of just a header file. Setting this
1258 # property avoids needing an empty .c file or an non-empty unnecessary .c
1259 # file.
1260 set_target_properties(libgnu PROPERTIES LINKER_LANGUAGE C)
1262 # Create /lib directory in the build directory and add it to the include path.
1263 file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/lib")
1264 target_include_directories(libgnu PUBLIC "${CMAKE_CURRENT_BINARY_DIR}/lib")
1266 # Include /lib from the source directory. It does no harm even if none of
1267 # the Gnulib replacements are used.
1268 target_include_directories(libgnu PUBLIC lib)
1270 # The command line tools need getopt_long in order to parse arguments. If
1271 # the system does not have a getopt_long implementation we can use the one
1272 # from Gnulib instead.
1273 check_symbol_exists(getopt_long getopt.h HAVE_GETOPT_LONG)
1275 if(NOT HAVE_GETOPT_LONG)
1276     # Set the __GETOPT_PREFIX definition to "rpl_" (replacement) to avoid
1277     # name conflicts with libc symbols. The same prefix is set if using
1278     # the Autotools build (m4/getopt.m4).
1279     target_compile_definitions(libgnu PUBLIC "__GETOPT_PREFIX=rpl_")
1281     # Create a custom copy command to copy the getopt header to the build
1282     # directory and re-copy it if it is updated. (Gnulib does it this way
1283     # because it allows choosing which .in.h files to actually use in the
1284     # build. We need just getopt.h so this is a bit overcomplicated for
1285     # a single header file only.)
1286     add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1287         COMMAND "${CMAKE_COMMAND}" -E copy
1288             "${CMAKE_CURRENT_SOURCE_DIR}/lib/getopt.in.h"
1289             "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1290         MAIN_DEPENDENCY "${CMAKE_CURRENT_SOURCE_DIR}/lib/getopt.in.h"
1291         VERBATIM)
1293     target_sources(libgnu PRIVATE
1294         lib/getopt1.c
1295         lib/getopt.c
1296         lib/getopt_int.h
1297         lib/getopt-cdefs.h
1298         lib/getopt-core.h
1299         lib/getopt-ext.h
1300         lib/getopt-pfx-core.h
1301         lib/getopt-pfx-ext.h
1302         "${CMAKE_CURRENT_BINARY_DIR}/lib/getopt.h"
1303     )
1304 endif()
1307 #############################################################################
1308 # xzdec
1309 #############################################################################
1311 if(HAVE_DECODERS AND (NOT MSVC OR MSVC_VERSION GREATER_EQUAL 1900))
1312     add_executable(xzdec
1313         src/common/sysdefs.h
1314         src/common/tuklib_common.h
1315         src/common/tuklib_config.h
1316         src/common/tuklib_exit.c
1317         src/common/tuklib_exit.h
1318         src/common/tuklib_gettext.h
1319         src/common/tuklib_progname.c
1320         src/common/tuklib_progname.h
1321         src/xzdec/xzdec.c
1322     )
1324     target_include_directories(xzdec PRIVATE
1325         src/common
1326         src/liblzma/api
1327     )
1329     target_link_libraries(xzdec PRIVATE liblzma libgnu)
1331     if(WIN32)
1332         # Add the Windows resource file for xzdec.exe.
1333         target_sources(xzdec PRIVATE src/xzdec/xzdec_w32res.rc)
1334         set_target_properties(xzdec PROPERTIES
1335             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1336         )
1337     endif()
1339     if(SANDBOX_COMPILE_DEFINITION)
1340         target_compile_definitions(xzdec PRIVATE
1341                                    "${SANDBOX_COMPILE_DEFINITION}")
1342     endif()
1344     tuklib_progname(xzdec)
1346     install(TARGETS xzdec
1347             RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1348                     COMPONENT xzdec)
1350     if(UNIX)
1351         install(FILES src/xzdec/xzdec.1
1352                 DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
1353                 COMPONENT xzdec)
1354     endif()
1355 endif()
1358 #############################################################################
1359 # xz
1360 #############################################################################
1362 if(NOT MSVC OR MSVC_VERSION GREATER_EQUAL 1900)
1363     add_executable(xz
1364         src/common/mythread.h
1365         src/common/sysdefs.h
1366         src/common/tuklib_common.h
1367         src/common/tuklib_config.h
1368         src/common/tuklib_exit.c
1369         src/common/tuklib_exit.h
1370         src/common/tuklib_gettext.h
1371         src/common/tuklib_integer.h
1372         src/common/tuklib_mbstr.h
1373         src/common/tuklib_mbstr_fw.c
1374         src/common/tuklib_mbstr_width.c
1375         src/common/tuklib_open_stdxxx.c
1376         src/common/tuklib_open_stdxxx.h
1377         src/common/tuklib_progname.c
1378         src/common/tuklib_progname.h
1379         src/xz/args.c
1380         src/xz/args.h
1381         src/xz/coder.c
1382         src/xz/coder.h
1383         src/xz/file_io.c
1384         src/xz/file_io.h
1385         src/xz/hardware.c
1386         src/xz/hardware.h
1387         src/xz/main.c
1388         src/xz/main.h
1389         src/xz/message.c
1390         src/xz/message.h
1391         src/xz/mytime.c
1392         src/xz/mytime.h
1393         src/xz/options.c
1394         src/xz/options.h
1395         src/xz/private.h
1396         src/xz/signals.c
1397         src/xz/signals.h
1398         src/xz/suffix.c
1399         src/xz/suffix.h
1400         src/xz/util.c
1401         src/xz/util.h
1402     )
1404     target_include_directories(xz PRIVATE
1405         src/common
1406         src/liblzma/api
1407     )
1409     if(HAVE_DECODERS)
1410         target_sources(xz PRIVATE
1411             src/xz/list.c
1412             src/xz/list.h
1413         )
1414     endif()
1416     target_link_libraries(xz PRIVATE liblzma libgnu)
1418     target_compile_definitions(xz PRIVATE ASSUME_RAM=128)
1420     if(WIN32)
1421         # Add the Windows resource file for xz.exe.
1422         target_sources(xz PRIVATE src/xz/xz_w32res.rc)
1423         set_target_properties(xz PROPERTIES
1424             LINK_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/common/common_w32res.rc"
1425         )
1426     endif()
1428     if(SANDBOX_COMPILE_DEFINITION)
1429         target_compile_definitions(xz PRIVATE "${SANDBOX_COMPILE_DEFINITION}")
1430     endif()
1432     tuklib_progname(xz)
1433     tuklib_mbstr(xz)
1435     check_symbol_exists(optreset getopt.h HAVE_OPTRESET)
1436     tuklib_add_definition_if(xz HAVE_OPTRESET)
1438     check_symbol_exists(posix_fadvise fcntl.h HAVE_POSIX_FADVISE)
1439     tuklib_add_definition_if(xz HAVE_POSIX_FADVISE)
1441     # How to get file time:
1442     check_struct_has_member("struct stat" st_atim.tv_nsec
1443                             "sys/types.h;sys/stat.h"
1444                             HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1445     if(HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1446         tuklib_add_definitions(xz HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1447     else()
1448         check_struct_has_member("struct stat" st_atimespec.tv_nsec
1449                                 "sys/types.h;sys/stat.h"
1450                                 HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1451         if(HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1452             tuklib_add_definitions(xz HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC)
1453         else()
1454             check_struct_has_member("struct stat" st_atimensec
1455                                     "sys/types.h;sys/stat.h"
1456                                     HAVE_STRUCT_STAT_ST_ATIMENSEC)
1457             tuklib_add_definition_if(xz HAVE_STRUCT_STAT_ST_ATIMENSEC)
1458         endif()
1459     endif()
1461     # How to set file time:
1462     check_symbol_exists(futimens "sys/types.h;sys/stat.h" HAVE_FUTIMENS)
1463     if(HAVE_FUTIMENS)
1464         tuklib_add_definitions(xz HAVE_FUTIMENS)
1465     else()
1466         check_symbol_exists(futimes "sys/time.h" HAVE_FUTIMES)
1467         if(HAVE_FUTIMES)
1468             tuklib_add_definitions(xz HAVE_FUTIMES)
1469         else()
1470             check_symbol_exists(futimesat "sys/time.h" HAVE_FUTIMESAT)
1471             if(HAVE_FUTIMESAT)
1472                 tuklib_add_definitions(xz HAVE_FUTIMESAT)
1473             else()
1474                 check_symbol_exists(utimes "sys/time.h" HAVE_UTIMES)
1475                 if(HAVE_UTIMES)
1476                     tuklib_add_definitions(xz HAVE_UTIMES)
1477                 else()
1478                     check_symbol_exists(_futime "sys/utime.h" HAVE__FUTIME)
1479                     if(HAVE__FUTIME)
1480                         tuklib_add_definitions(xz HAVE__FUTIME)
1481                     else()
1482                         check_symbol_exists(utime "utime.h" HAVE_UTIME)
1483                         tuklib_add_definition_if(xz HAVE_UTIME)
1484                     endif()
1485                 endif()
1486             endif()
1487         endif()
1488     endif()
1490     install(TARGETS xz
1491             RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
1492                     COMPONENT xz)
1494     if(UNIX)
1495         install(FILES src/xz/xz.1
1496                 DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
1497                 COMPONENT xz)
1499         option(CREATE_XZ_SYMLINKS "Create unxz and xzcat symlinks" ON)
1500         option(CREATE_LZMA_SYMLINKS "Create lzma, unlzma, and lzcat symlinks"
1501                ON)
1502         set(XZ_LINKS)
1504         if(CREATE_XZ_SYMLINKS)
1505             list(APPEND XZ_LINKS "unxz" "xzcat")
1506         endif()
1508         if(CREATE_LZMA_SYMLINKS)
1509             list(APPEND XZ_LINKS "lzma" "unlzma" "lzcat")
1510         endif()
1512         # With Windows Cygwin and MSYS2 the symlinking is complicated. Both
1513         # of these environments set the UNIX variable so they will try to
1514         # make the symlinks. The ability for Cygwin and MSYS2 to make
1515         # broken symlinks is determined by the CYGWIN and MSYS2 environment
1516         # variables, respectively. Broken symlinks are needed for the man
1517         # page symlinks and for determining if the xz and lzma symlinks need
1518         # to depend on the xz target or not. If broken symlinks cannot be
1519         # made then the xz binary must be created before the symlinks.
1520         set(ALLOW_BROKEN_SYMLINKS ON)
1522         if(CMAKE_SYSTEM_NAME STREQUAL "CYGWIN")
1523             # The Cygwin env variable can be set to four possible values:
1524             #
1525             # 1. "lnk". Create symlinks as Windows shortcuts.
1526             #
1527             # 2. "native". Create symlinks as native Windows symlinks
1528             #    if supported by the system. Fallback to "lnk" if native
1529             #    symlinks are not supported.
1530             #
1531             # 3. "nativestrict". Create symlinks as native Windows symlinks
1532             #    if supported by the system. If the target of the symlink
1533             #    does not exist or the creation of the symlink fails for any
1534             #    reason, do not create the symlink.
1535             #
1536             # 4. "sys". Create symlinks as plain files with a special
1537             #    system attribute containing the path to the symlink target.
1538             #
1539             # So, the only case we care about for broken symlinks is
1540             # "nativestrict" since all other values mean that broken
1541             # symlinks are allowed. If the env variable is not set the
1542             # default is "native". If the env variable is set but not
1543             # assigned one of the four values, then the default is the same
1544             # as option 1 "lnk".
1545             string(FIND "$ENV{CYGWIN}" "winsymlinks:nativestrict" SYMLINK_POS)
1546             if(SYMLINK_POS GREATER -1)
1547                 set(ALLOW_BROKEN_SYMLINKS OFF)
1548             endif()
1549         elseif(CMAKE_SYSTEM_NAME STREQUAL "MSYS")
1550             # The MSYS env variable behaves similar to the CYGWIN but has a
1551             # different default behavior. If winsymlinks is set but not
1552             # assigned one of the four supported values, the default is to
1553             # *copy* the target to the symlink destination. This will fail
1554             # if the target does not exist so broken symlinks cannot be
1555             # allowed.
1556             string(FIND "$ENV{MSYS}" "winsymlinks" SYMLINK_POS)
1557             if(SYMLINK_POS GREATER -1)
1558                 string(FIND "$ENV{MSYS}" "winsymlinks:nativestrict"
1559                         SYMLINK_POS)
1560                 if(SYMLINK_POS GREATER -1)
1561                     set(ALLOW_BROKEN_SYMLINKS OFF)
1562                 endif()
1563             else()
1564                 set(ALLOW_BROKEN_SYMLINKS OFF)
1565             endif()
1566         endif()
1568         # Create symlinks in the build directory and then install them.
1569         #
1570         # The symlinks do not likely need any special extension since
1571         # even on Windows the symlink can still be executed without
1572         # the .exe extension.
1573         foreach(LINK IN LISTS XZ_LINKS)
1574             add_custom_target("create_${LINK}" ALL
1575                 "${CMAKE_COMMAND}" -E create_symlink
1576                     "$<TARGET_FILE_NAME:xz>" "${LINK}"
1577                 BYPRODUCTS "${LINK}"
1578                 VERBATIM)
1579             install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${LINK}"
1580                     DESTINATION "${CMAKE_INSTALL_BINDIR}"
1581                     COMPONENT xz)
1583             # Only create the man page symlinks if the symlinks can be
1584             # created broken. The symlinks will not be valid until install
1585             # so they cannot be created on these system environments.
1586             if(ALLOW_BROKEN_SYMLINKS)
1587                 add_custom_target("create_${LINK}.1" ALL
1588                     "${CMAKE_COMMAND}" -E create_symlink "xz.1" "${LINK}.1"
1589                     BYPRODUCTS "${LINK}.1"
1590                     VERBATIM)
1591                 install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${LINK}.1"
1592                         DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
1593                         COMPONENT xz)
1594             else()
1595                 # Add the xz target as dependency when broken symlinks
1596                 # cannot be made. This ensures parallel builds do not fail
1597                 # since it will enforce the order of creating xz first, then
1598                 # the symlinks.
1599                 add_dependencies("create_${LINK}" xz)
1600             endif()
1601         endforeach()
1602     endif()
1603 endif()
1606 #############################################################################
1607 # Tests
1608 #############################################################################
1610 include(CTest)
1612 if(BUILD_TESTING)
1613     set(LIBLZMA_TESTS
1614         test_bcj_exact_size
1615         test_block_header
1616         test_check
1617         test_filter_flags
1618         test_filter_str
1619         test_hardware
1620         test_index
1621         test_index_hash
1622         test_lzip_decoder
1623         test_memlimit
1624         test_stream_flags
1625         test_vli
1626     )
1628     foreach(TEST IN LISTS LIBLZMA_TESTS)
1629         add_executable("${TEST}" "tests/${TEST}.c")
1631         target_include_directories("${TEST}" PRIVATE
1632             src/common
1633             src/liblzma/api
1634             src/liblzma
1635         )
1637         target_link_libraries("${TEST}" PRIVATE liblzma)
1639         # Put the test programs into their own subdirectory so they don't
1640         # pollute the top-level dir which might contain xz and xzdec.
1641         set_target_properties("${TEST}" PROPERTIES
1642             RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/tests_bin"
1643         )
1645         add_test(NAME "${TEST}"
1646                  COMMAND "${CMAKE_CURRENT_BINARY_DIR}/tests_bin/${TEST}"
1647         )
1649         # Set srcdir environment variable so that the tests find their
1650         # input files from the source tree.
1651         #
1652         # Set the return code for skipped tests to match Automake convention.
1653         set_tests_properties("${TEST}" PROPERTIES
1654             ENVIRONMENT "srcdir=${CMAKE_CURRENT_SOURCE_DIR}/tests"
1655             SKIP_RETURN_CODE 77
1656         )
1657     endforeach()
1658 endif()