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