forked from pvieito/PythonKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonLibrary.swift
More file actions
309 lines (272 loc) · 11.5 KB
/
PythonLibrary.swift
File metadata and controls
309 lines (272 loc) · 11.5 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
//===-- PythonLibrary.swift -----------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the logic for dynamically loading Python at runtime.
//
//===----------------------------------------------------------------------===//
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif os(Windows)
import CRT
import WinSDK
#endif
//===----------------------------------------------------------------------===//
// The `PythonLibrary` struct that loads Python symbols at runtime.
//===----------------------------------------------------------------------===//
public struct PythonLibrary {
public enum Error: Swift.Error, Equatable, CustomStringConvertible {
case pythonLibraryNotFound
public var description: String {
switch self {
case .pythonLibraryNotFound:
return """
Python library not found. Set the \(Environment.library.key) \
environment variable with the path to a Python library.
"""
}
}
}
private static let pythonInitializeSymbolName = "Py_Initialize"
private static let pythonLegacySymbolName = "PyString_AsString"
#if canImport(Darwin)
private static let defaultLibraryHandle = UnsafeMutableRawPointer(bitPattern: -2) // RTLD_DEFAULT
#else
private static let defaultLibraryHandle: UnsafeMutableRawPointer? = nil // RTLD_DEFAULT
#endif
private static var isPythonLibraryLoaded = false
private static var _pythonLibraryHandle: UnsafeMutableRawPointer?
private static var pythonLibraryHandle: UnsafeMutableRawPointer? {
try! PythonLibrary.loadLibrary()
return self._pythonLibraryHandle
}
/// Tries to load the Python library, will throw an error if no compatible library is found.
public static func loadLibrary() throws {
guard !self.isPythonLibraryLoaded else { return }
let pythonLibraryHandle = self.loadPythonLibrary()
guard self.isPythonLibraryLoaded(at: pythonLibraryHandle) else {
throw Error.pythonLibraryNotFound
}
self.isPythonLibraryLoaded = true
self._pythonLibraryHandle = pythonLibraryHandle
}
private static let isLegacyPython: Bool = {
let isLegacyPython = PythonLibrary.loadSymbol(PythonLibrary.pythonLibraryHandle, PythonLibrary.pythonLegacySymbolName) != nil
if isLegacyPython {
PythonLibrary.log("Loaded legacy Python library, using legacy symbols...")
}
return isLegacyPython
}()
internal static func loadSymbol<T>(
name: String, legacyName: String? = nil, type: T.Type = T.self) -> T {
var name = name
if let legacyName = legacyName, self.isLegacyPython {
name = legacyName
}
log("Loading symbol '\(name)' from the Python library...")
return unsafeBitCast(self.loadSymbol(self.pythonLibraryHandle, name), to: type)
}
}
// Methods of `PythonLibrary` required to load the Python library.
extension PythonLibrary {
private static let supportedMajorVersions: [Int] = [3, 2]
private static let supportedMinorVersions: [Int] = Array(0...30).reversed()
private static let libraryPathVersionCharacter: Character = ":"
#if canImport(Darwin)
private static var libraryNames = ["Python.framework/Versions/:/Python"]
private static var libraryPathExtensions = [""]
private static var librarySearchPaths = ["", "/opt/homebrew/Frameworks/", "/usr/local/Frameworks/"]
private static var libraryVersionSeparator = "."
#elseif os(Linux)
private static var libraryNames = ["libpython:", "libpython:m"]
private static var libraryPathExtensions = [".so"]
private static var librarySearchPaths = [""]
private static var libraryVersionSeparator = "."
#elseif os(Windows)
private static var libraryNames = ["python:"]
private static var libraryPathExtensions = [".dll"]
private static var librarySearchPaths = [""]
private static var libraryVersionSeparator = ""
#endif
private static let libraryPaths: [String] = {
var libraryPaths: [String] = []
for librarySearchPath in librarySearchPaths {
for libraryName in libraryNames {
for libraryPathExtension in libraryPathExtensions {
let libraryPath =
librarySearchPath + libraryName + libraryPathExtension
libraryPaths.append(libraryPath)
}
}
}
return libraryPaths
}()
private static func loadSymbol(
_ libraryHandle: UnsafeMutableRawPointer?, _ name: String) -> UnsafeMutableRawPointer? {
#if os(Windows)
guard let libraryHandle = libraryHandle else { return nil }
let moduleHandle = libraryHandle
.assumingMemoryBound(to: HINSTANCE__.self)
let moduleSymbol = GetProcAddress(moduleHandle, name)
return unsafeBitCast(moduleSymbol, to: UnsafeMutableRawPointer?.self)
#else
return dlsym(libraryHandle, name)
#endif
}
private static func isPythonLibraryLoaded(at pythonLibraryHandle: UnsafeMutableRawPointer? = nil) -> Bool {
let pythonLibraryHandle = pythonLibraryHandle ?? self.defaultLibraryHandle
return self.loadSymbol(pythonLibraryHandle, self.pythonInitializeSymbolName) != nil
}
private static func loadPythonLibrary() -> UnsafeMutableRawPointer? {
let pythonLibraryHandle: UnsafeMutableRawPointer?
if self.isPythonLibraryLoaded() {
pythonLibraryHandle = self.defaultLibraryHandle
}
else if let pythonLibraryPath = Environment.library.value {
pythonLibraryHandle = self.loadPythonLibrary(at: pythonLibraryPath)
}
else {
pythonLibraryHandle = self.findAndLoadExternalPythonLibrary()
}
return pythonLibraryHandle
}
private static func findAndLoadExternalPythonLibrary() -> UnsafeMutableRawPointer? {
for majorVersion in supportedMajorVersions {
for minorVersion in supportedMinorVersions {
for libraryPath in libraryPaths {
let version = PythonVersion(major: majorVersion, minor: minorVersion)
guard let pythonLibraryHandle = loadPythonLibrary(
at: libraryPath, version: version) else {
continue
}
return pythonLibraryHandle
}
}
}
return nil
}
private static func loadPythonLibrary(
at path: String, version: PythonVersion) -> UnsafeMutableRawPointer? {
let versionString = version.versionString
if let requiredPythonVersion = Environment.version.value {
let requiredMajorVersion = Int(requiredPythonVersion)
if requiredPythonVersion != versionString,
requiredMajorVersion != version.major {
return nil
}
}
let libraryVersionString = versionString
.split(separator: PythonVersion.versionSeparator)
.joined(separator: libraryVersionSeparator)
let path = path.split(separator: libraryPathVersionCharacter)
.joined(separator: libraryVersionString)
return self.loadPythonLibrary(at: path)
}
private static func loadPythonLibrary(at path: String) -> UnsafeMutableRawPointer? {
self.log("Trying to load library at '\(path)'...")
#if os(Windows)
let pythonLibraryHandle = UnsafeMutableRawPointer(LoadLibraryA(path))
#else
// Must be RTLD_GLOBAL because subsequent .so files from the imported python
// modules may depend on this .so file.
let pythonLibraryHandle = dlopen(path, RTLD_LAZY | RTLD_GLOBAL)
#endif
if pythonLibraryHandle != nil {
self.log("Library at '\(path)' was successfully loaded.")
}
return pythonLibraryHandle
}
}
// Methods of `PythonLibrary` required to set a given Python version or library path.
extension PythonLibrary {
private static func enforceNonLoadedPythonLibrary(function: String = #function) {
precondition(!self.isPythonLibraryLoaded, """
Error: \(function) should not be called after any Python library \
has already been loaded.
""")
}
/// Use the Python library with the specified version.
/// - Parameters:
/// - major: Major version or nil to use any Python version.
/// - minor: Minor version or nil to use any minor version.
public static func useVersion(_ major: Int?, _ minor: Int? = nil) {
self.enforceNonLoadedPythonLibrary()
let version = PythonVersion(major: major, minor: minor)
PythonLibrary.Environment.version.set(version.versionString)
}
/// Use the Python library at the specified path.
/// - Parameter path: Path of the Python library to load or nil to use the default search path.
public static func useLibrary(at path: String?) {
self.enforceNonLoadedPythonLibrary()
PythonLibrary.Environment.library.set(path ?? "")
}
}
// `PythonVersion` struct that defines a given Python version.
extension PythonLibrary {
private struct PythonVersion {
let major: Int?
let minor: Int?
static let versionSeparator: Character = "."
init(major: Int?, minor: Int?) {
precondition(!(major == nil && minor != nil), """
Error: The Python library minor version cannot be specified \
without the major version.
""")
self.major = major
self.minor = minor
}
var versionString: String {
guard let major = major else { return "" }
var versionString = String(major)
if let minor = minor {
versionString += "\(PythonVersion.versionSeparator)\(minor)"
}
return versionString
}
}
}
// `PythonLibrary.Environment` enum used to read and set environment variables.
extension PythonLibrary {
private enum Environment: String {
private static let keyPrefix = "PYTHON"
private static let keySeparator = "_"
case library = "LIBRARY"
case version = "VERSION"
case loaderLogging = "LOADER_LOGGING"
var key: String {
return Environment.keyPrefix + Environment.keySeparator + rawValue
}
var value: String? {
guard let cString = getenv(key) else { return nil }
let value = String(cString: cString)
guard !value.isEmpty else { return nil }
return value
}
func set(_ value: String) {
#if os(Windows)
_putenv_s(key, value)
#else
setenv(key, value, 1)
#endif
}
}
}
// Methods of `PythonLibrary` used for logging messages.
extension PythonLibrary {
private static func log(_ message: String) {
guard Environment.loaderLogging.value != nil else { return }
fputs(message + "\n", stderr)
}
}