Repository navigation
Expand file tree
/
Copy pathCMakeLists.txt
More file actions
438 lines (387 loc) · 18.1 KB
/
Copy pathCMakeLists.txt
File metadata and controls
438 lines (387 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
cmake_minimum_required(VERSION 3.15)
project(ddbc_bindings)
# Set C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Performance profiling instrumentation. OFF by default so released wheels ship
# with zero profiler code. Turn on with -DENABLE_PROFILING=ON (dev/internal builds).
option(ENABLE_PROFILING "Build with performance profiling instrumentation" OFF)
# Enable verbose output to see actual compiler/linker commands
set(CMAKE_VERBOSE_MAKEFILE ON CACHE BOOL "Verbose output" FORCE)
# Treat CMake warnings as errors
set(CMAKE_ERROR_DEPRECATED TRUE)
set(CMAKE_WARN_DEPRECATED TRUE)
if (MSVC)
# Security compiler options for OneBranch compliance
message(STATUS "Applying MSVC security compiler options for OneBranch compliance")
add_compile_options(
/GS # Buffer security check - detects buffer overruns
/guard:cf # Control Flow Guard - protects against control flow hijacking
)
add_link_options(
/DYNAMICBASE # ASLR - Address Space Layout Randomization
/NXCOMPAT # DEP - Data Execution Prevention
/GUARD:CF # Control Flow Guard (linker)
)
# SAFESEH only for x86 (32-bit) builds
if(CMAKE_SIZEOF_VOID_P EQUAL 4) # 32-bit
message(STATUS "Applying /SAFESEH for 32-bit build")
add_link_options(/SAFESEH) # Safe Structured Exception Handling
else()
message(STATUS "Skipping /SAFESEH (not applicable for 64-bit builds)")
endif()
# Enable PDB generation for all target types
add_compile_options("$<$<CONFIG:Release>:/Zi>")
add_link_options("$<$<CONFIG:Release>:/DEBUG /OPT:REF /OPT:ICF>")
message(STATUS "Security flags applied: /GS /guard:cf /DYNAMICBASE /NXCOMPAT /GUARD:CF")
endif()
# Detect platform
# TODO: Have a separate module/function for platform/distribution detection,
# Maybe a common python/cpp API
if(WIN32)
set(PLATFORM_NAME "windows")
elseif(APPLE)
set(PLATFORM_NAME "macos")
elseif(UNIX)
set(PLATFORM_NAME "linux")
else()
message(FATAL_ERROR "Unsupported platform")
endif()
# Set default architecture if not provided
if(NOT DEFINED ARCHITECTURE)
if(WIN32)
# Default to x64 for Windows
set(ARCHITECTURE "win64")
elseif(APPLE)
# Always use universal2 for macOS
set(ARCHITECTURE "universal2")
else()
# Default to x64 for other platforms
set(ARCHITECTURE "x64")
endif()
endif()
# Add platform and architecture to compiler definitions
add_definitions(-DARCHITECTURE="${ARCHITECTURE}")
add_definitions(-DPLATFORM_NAME="${PLATFORM_NAME}")
# --- msodbcsql driver version (single source of truth) -----------------------
# The ODBC driver filename embeds the msodbcsql version (e.g.
# libmsodbcsql-18.6.so.2.1 on Linux, libmsodbcsql.18.dylib on macOS,
# msodbcsql18.dll on Windows). Derive that version from
# mssql_python_odbc.__version__ -- the single source of truth for the driver
# version -- and inject it into GetDriverPathCpp() via -D defines, so the native
# resolver and the Python package can never drift. The literal is read straight
# from the file (not by importing the package) to keep configure hermetic and
# independent of whatever packages the build interpreter happens to have.
set(MSODBCSQL_VERSION_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/../../mssql_python_odbc/__init__.py")
if(NOT EXISTS "${MSODBCSQL_VERSION_SOURCE}")
message(FATAL_ERROR
"Cannot resolve the msodbcsql driver version: ${MSODBCSQL_VERSION_SOURCE} not found. "
"The native driver filename is derived from mssql_python_odbc.__version__; "
"build from a full repository checkout.")
endif()
file(STRINGS "${MSODBCSQL_VERSION_SOURCE}" _msodbcsql_version_line REGEX "^__version__")
# Capture the full quoted version literal (e.g. 18.6.2, 18.6.2.1, 18.6.2.post1).
# Only a leading MAJOR.MINOR.PATCH must be numeric; a trailing packaging-revision
# component or PEP 440 suffix is allowed because mssql-python-odbc ships
# metadata-only re-releases as e.g. 18.6.2.1. The native driver filename is
# derived solely from MAJOR and MAJOR.MINOR below, so a trailing revision has no
# effect on which driver is loaded.
string(REGEX REPLACE ".*['\"]([^'\"]+)['\"].*" "\\1"
MSODBCSQL_VERSION "${_msodbcsql_version_line}")
if(NOT MSODBCSQL_VERSION MATCHES "^[0-9]+\\.[0-9]+\\.[0-9]+")
message(FATAL_ERROR
"Failed to parse __version__ from ${MSODBCSQL_VERSION_SOURCE} "
"(got '${MSODBCSQL_VERSION}'); expected a leading MAJOR.MINOR.PATCH.")
endif()
string(REGEX MATCH "^[0-9]+" MSODBCSQL_VERSION_MAJOR "${MSODBCSQL_VERSION}")
string(REGEX MATCH "^[0-9]+\\.[0-9]+" MSODBCSQL_VERSION_MAJOR_MINOR "${MSODBCSQL_VERSION}")
message(STATUS "msodbcsql driver version (from mssql_python_odbc.__version__): ${MSODBCSQL_VERSION} -> major=${MSODBCSQL_VERSION_MAJOR}, major.minor=${MSODBCSQL_VERSION_MAJOR_MINOR}")
add_definitions(-DMSODBCSQL_VERSION_MAJOR="${MSODBCSQL_VERSION_MAJOR}")
add_definitions(-DMSODBCSQL_VERSION_MAJOR_MINOR="${MSODBCSQL_VERSION_MAJOR_MINOR}")
# For macOS, always set universal build
if(APPLE)
set(CMAKE_OSX_ARCHITECTURES "arm64;x86_64" CACHE STRING "Build architectures for macOS" FORCE)
message(STATUS "Setting universal2 build for macOS (arm64 + x86_64)")
endif()
# Get Python version and platform info
execute_process(
COMMAND python -c "import sys; print(f'{sys.version_info.major}{sys.version_info.minor}')"
OUTPUT_VARIABLE PYTHON_VERSION
OUTPUT_STRIP_TRAILING_WHITESPACE
)
# Map the architecture to a format similar to what wheels use
if(WIN32)
# Windows architecture mapping
if(CMAKE_GENERATOR_PLATFORM STREQUAL "ARM64" OR DEFINED ENV{BUILD_ARM64})
set(WHEEL_ARCH "arm64")
elseif(ARCHITECTURE STREQUAL "win64" OR ARCHITECTURE STREQUAL "amd64" OR ARCHITECTURE STREQUAL "x64")
set(WHEEL_ARCH "amd64")
elseif(ARCHITECTURE STREQUAL "win32" OR ARCHITECTURE STREQUAL "x86")
set(WHEEL_ARCH "win32")
else()
message(FATAL_ERROR "Unsupported Windows architecture: ${ARCHITECTURE}. Supported architectures are win32, win64, x86, amd64, arm64.")
endif()
elseif(APPLE)
message(STATUS "Setting macOS wheel architecture to universal2")
# macOS always uses universal2
set(WHEEL_ARCH "universal2")
else()
message(STATUS "Setting Linux wheel architecture based on detected architecture (${ARCHITECTURE})")
# Linux architecture mapping
if(ARCHITECTURE STREQUAL "arm64" OR ARCHITECTURE STREQUAL "aarch64")
set(WHEEL_ARCH "arm64")
message(STATUS "Setting Linux wheel architecture to arm64")
else()
set(WHEEL_ARCH "x86_64")
message(STATUS "Setting Linux wheel architecture to x86_64")
endif()
endif()
# Get Python and pybind11 include paths
if(DEFINED PYTHON_INCLUDE_DIR AND NOT "${PYTHON_INCLUDE_DIR}" STREQUAL "")
message(STATUS "Using provided Python include directory: ${PYTHON_INCLUDE_DIR}")
else()
# Try to detect Python include directory
execute_process(
COMMAND python -c "import sysconfig; print(sysconfig.get_path('include'))"
OUTPUT_VARIABLE PYTHON_INCLUDE_DIR
OUTPUT_STRIP_TRAILING_WHITESPACE
)
message(STATUS "Auto-detected Python include directory: ${PYTHON_INCLUDE_DIR}")
endif()
if(DEFINED PYBIND11_INCLUDE_DIR AND NOT "${PYBIND11_INCLUDE_DIR}" STREQUAL "")
message(STATUS "Using provided pybind11 include directory: ${PYBIND11_INCLUDE_DIR}")
else()
# Try to detect pybind11 include directory
execute_process(
COMMAND python -c "import pybind11; print(pybind11.get_include())"
OUTPUT_VARIABLE PYBIND11_INCLUDE_DIR
OUTPUT_STRIP_TRAILING_WHITESPACE
)
message(STATUS "Auto-detected pybind11 include directory: ${PYBIND11_INCLUDE_DIR}")
endif()
# Find Python Library for linking
execute_process(
COMMAND python -c "import sysconfig; print(sysconfig.get_config_var('LIBDIR'))"
OUTPUT_VARIABLE PYTHON_LIB_DIR
OUTPUT_STRIP_TRAILING_WHITESPACE
)
message(STATUS "Python LIBDIR from sysconfig: ${PYTHON_LIB_DIR}")
# On macOS, we may need additional work to find the Python library
if(APPLE AND (NOT PYTHON_LIB_DIR OR "${PYTHON_LIB_DIR}" STREQUAL ""))
message(STATUS "LIBDIR is None or empty, trying alternative methods")
# Get Python executable path
execute_process(
COMMAND python -c "import sys; print(sys.executable)"
OUTPUT_VARIABLE PYTHON_EXECUTABLE
OUTPUT_STRIP_TRAILING_WHITESPACE
)
# Get the directory containing the Python executable
get_filename_component(PYTHON_BIN_DIR "${PYTHON_EXECUTABLE}" DIRECTORY)
message(STATUS "Python executable directory: ${PYTHON_BIN_DIR}")
# Try to find the library in or near the executable directory
set(POTENTIAL_PYTHON_LIB_DIRS
"${PYTHON_BIN_DIR}/../lib"
"${PYTHON_BIN_DIR}/../../lib"
"/Library/Frameworks/Python.framework/Versions/Current/lib"
)
# Get Python version for library name
execute_process(
COMMAND python -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"
OUTPUT_VARIABLE PYTHON_VERSION_FULL
OUTPUT_STRIP_TRAILING_WHITESPACE
)
set(PYTHON_LIBRARY "")
foreach(LIB_DIR ${POTENTIAL_PYTHON_LIB_DIRS})
message(STATUS "Checking for Python library in ${LIB_DIR}")
if(EXISTS "${LIB_DIR}/libpython${PYTHON_VERSION_FULL}.dylib")
set(PYTHON_LIBRARY "${LIB_DIR}/libpython${PYTHON_VERSION_FULL}.dylib")
break()
endif()
endforeach()
if(PYTHON_LIBRARY)
message(STATUS "Found Python library: ${PYTHON_LIBRARY}")
else()
message(STATUS "Python library not found in standard locations, will try using framework")
# When using a framework, we don't specify the library directly
endif()
elseif(WIN32 AND (NOT PYTHON_LIB_DIR OR "${PYTHON_LIB_DIR}" STREQUAL "" OR "${PYTHON_LIB_DIR}" STREQUAL "None"))
# On Windows, if PYTHON_LIB_DIR is not set, we will try to find it using sysconfig
message(STATUS "PYTHON_LIB_DIR is None or empty for Windows, trying to find it using sysconfig")
# Use Python Executable to find the library directory
execute_process(
COMMAND python -c "import sys, os; print(os.path.dirname(sys.executable))"
OUTPUT_VARIABLE PYTHON_EXEC_DIR
OUTPUT_STRIP_TRAILING_WHITESPACE
)
message(STATUS "Python executable directory: ${PYTHON_EXEC_DIR}")
# Set the library directory based on the executable directory
set(PYTHON_LIB_DIR "${PYTHON_EXEC_DIR}/libs")
message(STATUS "Using Python library directory: ${PYTHON_LIB_DIR}")
endif()
if(DEFINED ENV{CUSTOM_PYTHON_LIB_DIR} AND NOT "$ENV{CUSTOM_PYTHON_LIB_DIR}" STREQUAL "" AND NOT "$ENV{CUSTOM_PYTHON_LIB_DIR}" STREQUAL "None")
message(STATUS "CUSTOM_PYTHON_LIB_DIR is set, using it")
set(PYTHON_LIB_DIR $ENV{CUSTOM_PYTHON_LIB_DIR})
message(STATUS "Using custom Python library directory: ${PYTHON_LIB_DIR}")
endif()
message(STATUS "Final Python library directory: ${PYTHON_LIB_DIR}")
# Single-config POSIX generators ignore `cmake --build --config Release`.
# Make the optimized release mode explicit instead of relying on simdutf to
# populate this project-wide cache variable as a FetchContent side effect.
if(UNIX AND NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
endif()
include(FetchContent)
message(STATUS "Downloading simdutf v8.2.0 source archive with FetchContent")
set(simdutf_fetchcontent_args
URL https://github.com/simdutf/simdutf/archive/refs/tags/v8.2.0.tar.gz
URL_HASH SHA256=033a91b1d7d1cb818c1eff49e61faaa1b64a3a530d59ef9efef0195e56bda8b1
)
if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.24")
list(APPEND simdutf_fetchcontent_args DOWNLOAD_EXTRACT_TIMESTAMP FALSE)
endif()
FetchContent_Declare(simdutf ${simdutf_fetchcontent_args})
set(SIMDUTF_TESTS OFF CACHE BOOL "Disable simdutf tests" FORCE)
set(SIMDUTF_TOOLS OFF CACHE BOOL "Disable simdutf tools" FORCE)
set(SIMDUTF_BENCHMARKS OFF CACHE BOOL "Disable simdutf benchmarks" FORCE)
FetchContent_MakeAvailable(simdutf)
set(DDBC_SOURCE "ddbc_bindings.cpp")
message(STATUS "Using standard source file: ${DDBC_SOURCE}")
# Include connection module and logger bridge
add_library(ddbc_bindings MODULE ${DDBC_SOURCE} connection/connection.cpp connection/connection_pool.cpp logger_bridge.cpp)
# Set the output name to include Python version and architecture
# Use appropriate file extension based on platform
if(WIN32)
set(MODULE_EXTENSION ".pyd")
else()
# macOS and Linux both use .so for Python extensions
set(MODULE_EXTENSION ".so")
endif()
# Set the output name based on the Python version and architecture
set_target_properties(ddbc_bindings PROPERTIES
PREFIX ""
OUTPUT_NAME "ddbc_bindings.cp${PYTHON_VERSION}-${WHEEL_ARCH}"
SUFFIX "${MODULE_EXTENSION}"
)
# Ensure PDB is generated in Release
set_target_properties(ddbc_bindings PROPERTIES
COMPILE_PDB_NAME "ddbc_bindings.cp${PYTHON_VERSION}-${WHEEL_ARCH}"
COMPILE_PDB_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
PDB_NAME "ddbc_bindings.cp${PYTHON_VERSION}-${WHEEL_ARCH}"
PDB_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
)
# Include directories for all architectures
if(NOT DEFINED ODBC_INCLUDE_DIR)
if(APPLE)
# On macOS, try to find ODBC headers in Homebrew's location
message(STATUS "ODBC_INCLUDE_DIR not specified, trying Homebrew location")
set(ODBC_INCLUDE_DIR "/opt/homebrew/include")
endif()
endif()
message(STATUS "Using ODBC include directory: ${ODBC_INCLUDE_DIR}")
# Configure target include directories and link libraries
target_include_directories(ddbc_bindings PRIVATE
${CMAKE_CURRENT_SOURCE_DIR} # Root directory (for ddbc_bindings.h)
${CMAKE_CURRENT_SOURCE_DIR}/connection # connection directory (for connection.h)
${PYTHON_INCLUDE_DIR}
${PYBIND11_INCLUDE_DIR}
)
if(APPLE)
# Add ODBC include directories on macOS
target_include_directories(ddbc_bindings PRIVATE ${CMAKE_SOURCE_DIR}/../libs/odbc_include ${ODBC_INCLUDE_DIR})
# For macOS, always use dynamic lookup for Python symbols
# This ensures the extension works in any Python environment including virtual environments
message(STATUS "Using dynamic lookup for Python symbols on macOS (best practice for Python extensions)")
set_target_properties(ddbc_bindings PROPERTIES LINK_FLAGS "-undefined dynamic_lookup")
target_link_libraries(ddbc_bindings PRIVATE dl)
# Set macOS-specific compile options
target_compile_options(ddbc_bindings PRIVATE
-Wno-unused-value
-Wno-deprecated-declarations
)
else()
# For other platforms, use standard include and link setup
# target_include_directories(ddbc_bindings PRIVATE ${ODBC_INCLUDE_DIR})
if(WIN32 AND DEFINED PYTHON_LIB_DIR)
# On Windows, link with the Python lib
if(EXISTS "${PYTHON_LIB_DIR}/python${PYTHON_VERSION}.lib")
message(STATUS "Found Python library: ${PYTHON_LIB_DIR}/python${PYTHON_VERSION}.lib")
target_link_libraries(ddbc_bindings PRIVATE "${PYTHON_LIB_DIR}/python${PYTHON_VERSION}.lib")
elseif(EXISTS "${PYTHON_LIB_DIR}/python${PYTHON_VERSION_MAJOR}${PYTHON_VERSION_MINOR}.lib")
message(STATUS "Found Python library: ${PYTHON_LIB_DIR}/python${PYTHON_VERSION_MAJOR}${PYTHON_VERSION_MINOR}.lib")
target_link_libraries(ddbc_bindings PRIVATE "${PYTHON_LIB_DIR}/python${PYTHON_VERSION_MAJOR}${PYTHON_VERSION_MINOR}.lib")
endif()
endif()
endif()
target_link_libraries(ddbc_bindings PRIVATE simdutf::simdutf)
# Compiler definitions
target_compile_definitions(ddbc_bindings PRIVATE
HAVE_SNPRINTF
_USE_MATH_DEFINES
PYBIND11_COMPILER_TYPE="_MSC_VER"
NOMINMAX
)
# Emit ENABLE_PROFILING to the compiler only when the option is on.
if(ENABLE_PROFILING)
message(STATUS "Building WITH performance profiling instrumentation")
target_compile_definitions(ddbc_bindings PRIVATE ENABLE_PROFILING)
endif()
# Add warning level flags for MSVC
if(MSVC)
target_compile_options(ddbc_bindings PRIVATE /W4 /WX)
endif()
# Add warning flags for GCC/Clang on Linux and macOS
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR
CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang")
target_compile_options(ddbc_bindings PRIVATE
-Werror # Treat warnings as errors
-Wattributes # Enable attribute warnings (cross-compiler)
-Wformat=2 # Check nonliteral formats and printf argument types
-Werror=format-security # Explicitly keep format-security diagnostics fatal
)
# GCC-specific warning flags
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
target_compile_options(ddbc_bindings PRIVATE
-Wint-to-pointer-cast # GCC-specific warning for integer-to-pointer casts
)
endif()
endif()
# Harden the Python extension against exploitation of a separate memory-safety
# defect. Mach-O receives stack protection; ELF-specific flags stay Linux-only.
if(UNIX)
target_compile_options(ddbc_bindings PRIVATE -fstack-protector-strong)
endif()
if(UNIX AND NOT APPLE)
include(CheckCXXSourceCompiles)
set(DDBC_REQUIRED_FLAGS_SAVED "${CMAKE_REQUIRED_FLAGS}")
set(CMAKE_REQUIRED_FLAGS
"${CMAKE_REQUIRED_FLAGS} -O2 -Werror -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3"
)
check_cxx_source_compiles("
#include <features.h>
#if !defined(__USE_FORTIFY_LEVEL) || __USE_FORTIFY_LEVEL < 3
#error _FORTIFY_SOURCE=3 is unavailable
#endif
int main() { return 0; }
" DDBC_SUPPORTS_FORTIFY_SOURCE_3)
set(CMAKE_REQUIRED_FLAGS "${DDBC_REQUIRED_FLAGS_SAVED}")
if(DDBC_SUPPORTS_FORTIFY_SOURCE_3)
set(DDBC_FORTIFY_LEVEL 3)
else()
set(DDBC_FORTIFY_LEVEL 2)
endif()
target_compile_options(ddbc_bindings PRIVATE
$<$<NOT:$<CONFIG:Debug>>:-U_FORTIFY_SOURCE>
$<$<NOT:$<CONFIG:Debug>>:-D_FORTIFY_SOURCE=${DDBC_FORTIFY_LEVEL}>
)
target_link_options(ddbc_bindings PRIVATE
-Wl,-z,relro
-Wl,-z,now
-Wl,-z,noexecstack
)
endif()
# Add macOS-specific string conversion fix
if(APPLE)
message(STATUS "Enabling macOS string conversion fix")
target_compile_definitions(ddbc_bindings PRIVATE MACOS_STRING_FIX)
target_compile_options(ddbc_bindings PRIVATE -DAPPLE_SILICON)
endif()