permitplane-client 0.1.0.alpha.1-x64-mingw-ucrt

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,174 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PermitPlane
4
+ # Application licensing client. Use .open with a block, or call #close.
5
+ class Client
6
+ SCOPE = { user: 0, machine: 1 }.freeze
7
+ OFFLINE = { activate: 1, deactivate: 2 }.freeze
8
+ APPROVAL = %i[none waiting completed denied expired cancelled].freeze
9
+ CONFIG_LIMIT = 1 << 20
10
+
11
+ def self.open(config, **options)
12
+ client = nil
13
+ Thread.handle_interrupt(Exception => :never) { client = new(config, **options) }
14
+ return client unless block_given?
15
+
16
+ yield client
17
+ ensure
18
+ client&.close if block_given?
19
+ end
20
+
21
+ def self.read_config(path)
22
+ path = Native.absolute_path(path)
23
+ Native.text(File.open(path, "rb") { |file| file.read(CONFIG_LIMIT + 1) || "" }, max: CONFIG_LIMIT)
24
+ end
25
+
26
+ def self.check_callback!
27
+ raise LifecycleError, "PermitPlane calls are forbidden from a native callback" if HostAdapter.in_callback?
28
+ end
29
+
30
+ def initialize(config, host: nil, library_path: nil, scope: :user, state_directory: nil)
31
+ self.class.check_callback!
32
+ if host && (state_directory || scope != :user)
33
+ raise ArgumentError, "native host options require the built-in host"
34
+ end
35
+
36
+ @pid = Process.pid
37
+ @mutex = Mutex.new
38
+ @native = Native.new(library_path, callbacks: !host.nil?)
39
+ config = Native.json(config)
40
+ Thread.handle_interrupt(Exception => :never) do
41
+ @handle = if host
42
+ @host_adapter = HostAdapter.new(host)
43
+ @native.handle(:client_new, config, @host_adapter.table)
44
+ else
45
+ directory = Native.absolute_path(state_directory) unless state_directory.nil?
46
+ @native.handle(:client_new_default, config, SCOPE.fetch(scope), directory)
47
+ end
48
+ end
49
+ rescue Exception
50
+ if @handle
51
+ @native.call(:client_free, @handle)
52
+ @handle = nil
53
+ end
54
+ raise
55
+ end
56
+
57
+ def close
58
+ guard!
59
+ @mutex.synchronize do
60
+ Thread.handle_interrupt(Exception => :never) do
61
+ if @handle
62
+ @native.call(:client_free, @handle)
63
+ @handle = nil
64
+ @host_adapter = nil
65
+ end
66
+ end
67
+ end
68
+ nil
69
+ end
70
+
71
+ def closed?
72
+ guard!
73
+ @mutex.synchronize { @handle.nil? }
74
+ end
75
+
76
+ def activate_with_key(key, device_name: nil)
77
+ invoke(:activate_with_key, Native.text(key), Native.optional_text(device_name))
78
+ end
79
+
80
+ def start_hosted_approval(device_name: nil)
81
+ invoke(:start_hosted_approval, Native.optional_text(device_name))
82
+ end
83
+
84
+ def start_vendor_enrollment(device_name: nil)
85
+ invoke(:start_vendor_enrollment, Native.optional_text(device_name))
86
+ end
87
+
88
+ def pending_approval
89
+ read_json(:client_pending_approval)
90
+ end
91
+
92
+ def advance_approval
93
+ with_handle do |handle|
94
+ out = Native.buffer(4)
95
+ check(@native.call(:client_advance_approval, handle, out), handle)
96
+ APPROVAL.fetch(out[0, 4].unpack1("L")) { raise LoadError, "unknown native approval status" }
97
+ end
98
+ end
99
+
100
+ def checkout_seat(borrow_hours: 0)
101
+ invoke(:checkout_seat, Native.integer(borrow_hours, 0..504))
102
+ end
103
+
104
+ def create_offline_request(kind, device_name: nil)
105
+ with_handle do |handle|
106
+ @native.output(:client_create_offline_request, handle, OFFLINE.fetch(kind),
107
+ Native.optional_text(device_name), capacity: 8193)
108
+ end
109
+ end
110
+
111
+ def import_offline_response(text)
112
+ invoke(:import_offline_response, Native.text(text))
113
+ end
114
+
115
+ def has_feature(code)
116
+ with_handle do |handle|
117
+ @native.scalar(:client_has_feature, handle, Native.text(code), format: "C") == 1
118
+ end
119
+ end
120
+
121
+ def feature_value(code)
122
+ with_handle { |handle| @native.limit(:client_feature_value, handle, Native.text(code)) }
123
+ end
124
+
125
+ def status
126
+ read_json(:client_status)
127
+ end
128
+
129
+ def last_error
130
+ read_json(:client_last_error)
131
+ end
132
+
133
+ %i[cancel_approval refresh deactivate renew_seat release_seat persist].each do |operation|
134
+ define_method(operation) { invoke(operation) }
135
+ end
136
+
137
+ private
138
+
139
+ def initialize_copy(_)
140
+ raise LifecycleError, "PermitPlane clients cannot be copied"
141
+ end
142
+
143
+ def guard!
144
+ raise LifecycleError, "Open a new PermitPlane client after fork" unless Process.pid == @pid
145
+
146
+ self.class.check_callback!
147
+ end
148
+
149
+ def with_handle
150
+ guard!
151
+ @mutex.synchronize do
152
+ raise LifecycleError, "PermitPlane client is closed" unless @handle
153
+
154
+ Thread.handle_interrupt(Exception => :never) { yield @handle }
155
+ end
156
+ end
157
+
158
+ def invoke(name, *arguments)
159
+ with_handle { |handle| check(@native.call(:"client_#{name}", handle, *arguments), handle) }
160
+ nil
161
+ end
162
+
163
+ def check(result, handle)
164
+ return if result.zero?
165
+
166
+ details = JSON.parse(@native.output(:client_last_error, handle))
167
+ @native.check(result, details)
168
+ end
169
+
170
+ def read_json(name)
171
+ with_handle { |handle| JSON.parse(@native.output(name, handle)) }
172
+ end
173
+ end
174
+ end
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module PermitPlane
6
+ # Native callback adapter. The application supplies protected host services.
7
+ class HostAdapter
8
+ MAX_HEADERS = 16 * 1024
9
+
10
+ def self.in_callback?
11
+ Thread.current.thread_variable_get(Native::CALLBACK_THREAD)
12
+ end
13
+
14
+ def initialize(host)
15
+ @host = host
16
+ @table = Native::HOST.malloc(Fiddle::RUBY_FREE)
17
+ @table.struct_size = Native::HOST.size
18
+ @table.user_data = 0
19
+ p = Native::P
20
+ size = Native::S
21
+ @closures = []
22
+ bind(:state_load, [p, size, p]) do |buffer, capacity, length|
23
+ state = Native.invoke_host { Native.optional_text(@host.state_load) }
24
+ next 1 if state.nil?
25
+
26
+ length[0, Fiddle::SIZEOF_SIZE_T] = [state.bytesize].pack("J")
27
+ next 101 if state.bytesize > capacity
28
+
29
+ buffer[0, state.bytesize] = state
30
+ 0
31
+ end
32
+ bind(:state_save, [p, size]) do |buffer, length|
33
+ state = Native.text(buffer[0, Native.integer(length, 0..Native::MAX_BYTES)])
34
+ Native.invoke_host { @host.state_save(state) }
35
+ 0
36
+ end
37
+ bind(:state_clear, []) do
38
+ Native.invoke_host { @host.state_clear }
39
+ 0
40
+ end
41
+ bind(:key_init, [p, p]) do |namespace, out|
42
+ name = Native.text(namespace.to_s)
43
+ key = Native.invoke_host { Native.bytes(@host.key_init(name), 64) }
44
+ out[0, 64] = key
45
+ 0
46
+ end
47
+ bind(:key_sign, [p, p]) do |digest, out|
48
+ input = digest[0, 32]
49
+ signature = Native.invoke_host { Native.bytes(@host.key_sign(input), 64) }
50
+ out[0, 64] = signature
51
+ 0
52
+ end
53
+ bind(:clock_observe, [p]) { |out| observe(out) }
54
+ bind(:http_send, [p, p]) { |request, response| send_http(request, response) }
55
+ end
56
+
57
+ attr_reader :table
58
+
59
+ private
60
+
61
+ def bind(name, parameters, &block)
62
+ closure = Native.callback([Native::P, *parameters], &block)
63
+ @closures << closure
64
+ @table.public_send("#{name}=", closure.to_i)
65
+ end
66
+
67
+ def observe(pointer)
68
+ milliseconds, confident, id = Native.invoke_host do
69
+ data = @host.clock_observe
70
+ [Native.integer(data.fetch(:monotonic_ms), 0...(1 << 63)), Native.boolean(data.fetch(:confident)),
71
+ Native.text(data.fetch(:boot_id), max: 63)]
72
+ end
73
+ sample = Native::CLOCK.new(pointer)
74
+ sample.monotonic_ms = milliseconds
75
+ sample.confident = confident
76
+ pointer[Native::CLOCK.offsetof("boot_id"), 64] = id.b.ljust(64, "\0")
77
+ 0
78
+ end
79
+
80
+ def send_http(input, output)
81
+ request = Native::REQUEST.new(input)
82
+ url = Native.text(request.url.to_s)
83
+ uri = URI.parse(url)
84
+ raise ArgumentError, "an HTTPS URL is required" unless uri.is_a?(URI::HTTPS) && uri.host && !uri.userinfo
85
+
86
+ response = Native::RESPONSE.new(output)
87
+ length = Native.integer(request.body_len, 0..Native::MAX_BYTES)
88
+ arguments = {
89
+ method: Native.text(request.http_method.to_s),
90
+ url: url,
91
+ headers: Native.text(request.headers.to_s, max: MAX_HEADERS),
92
+ body: request.body.null? ? nil : request.body[0, length],
93
+ timeout_ms: request.timeout_ms
94
+ }
95
+ header_capacity = response.headers_cap
96
+ body_capacity = response.body_cap
97
+ status, headers, body = Native.invoke_host do
98
+ result = @host.http_send(**arguments)
99
+ body = result.fetch(:body, "")
100
+ raise ArgumentError, "response body is too large" unless body.is_a?(String) && body.bytesize <= body_capacity
101
+
102
+ [Native.integer(result.fetch(:status), 100..599),
103
+ Native.text(result.fetch(:headers, ""), max: header_capacity), body.b.freeze]
104
+ end
105
+
106
+ response.headers[0, headers.bytesize] = headers
107
+ response.body[0, body.bytesize] = body
108
+ response.headers_len = headers.bytesize
109
+ response.body_len = body.bytesize
110
+ response.status = status
111
+ 0
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,56 @@
1
+ {
2
+ "target": "win_amd64",
3
+ "sha256": "e80e5efe07c20d07adf72118718f93273100053393bf0b6a5ad7dd0762625830",
4
+ "bytes": 1128960,
5
+ "abi": 1,
6
+ "exports": [
7
+ "pp_abi_version",
8
+ "pp_client_activate_with_key",
9
+ "pp_client_advance_approval",
10
+ "pp_client_cancel_approval",
11
+ "pp_client_checkout_seat",
12
+ "pp_client_create_offline_request",
13
+ "pp_client_deactivate",
14
+ "pp_client_feature_value",
15
+ "pp_client_free",
16
+ "pp_client_has_feature",
17
+ "pp_client_import_offline_response",
18
+ "pp_client_last_error",
19
+ "pp_client_new",
20
+ "pp_client_new_default",
21
+ "pp_client_open_default",
22
+ "pp_client_pending_approval",
23
+ "pp_client_persist",
24
+ "pp_client_refresh",
25
+ "pp_client_release_seat",
26
+ "pp_client_renew_seat",
27
+ "pp_client_start_hosted_approval",
28
+ "pp_client_start_vendor_enrollment",
29
+ "pp_client_status",
30
+ "pp_grant_claims_json",
31
+ "pp_grant_free",
32
+ "pp_grant_get_info",
33
+ "pp_grant_has_feature",
34
+ "pp_grant_lease_expires",
35
+ "pp_grant_lease_kind",
36
+ "pp_grant_limit",
37
+ "pp_grant_verify",
38
+ "pp_keyset_free",
39
+ "pp_keyset_new",
40
+ "pp_license_file_claims_json",
41
+ "pp_license_file_free",
42
+ "pp_license_file_has_feature",
43
+ "pp_license_file_limit",
44
+ "pp_license_file_verify",
45
+ "pp_license_key_normalize",
46
+ "pp_proof_build",
47
+ "pp_proof_verify",
48
+ "pp_receipt_time",
49
+ "pp_replay_set_free",
50
+ "pp_replay_set_insert",
51
+ "pp_replay_set_new",
52
+ "pp_status_code",
53
+ "pp_thumbprint",
54
+ "pp_trusted_now"
55
+ ]
56
+ }
@@ -0,0 +1,307 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fiddle"
4
+ require "fiddle/import"
5
+ require "json"
6
+ require "rbconfig"
7
+ require "rubygems"
8
+
9
+ module PermitPlane
10
+ class Error < StandardError
11
+ attr_reader :status, :code, :details
12
+
13
+ def initialize(status, code, details = nil)
14
+ @status = status
15
+ @code = code
16
+ @details = details
17
+ super("PermitPlane: #{code}")
18
+ end
19
+ end
20
+
21
+ class LoadError < StandardError; end
22
+ class LifecycleError < StandardError; end
23
+
24
+ # Internal ABI and memory handling shared by client, verification and host adapters.
25
+ class Native
26
+ extend Fiddle::Importer
27
+
28
+ ABI = 1
29
+ BUFFER_TOO_SMALL = 101
30
+ MAX_BYTES = 1 << 20
31
+ CALLBACK_THREAD = :permitplane_native_callback
32
+
33
+ P = Fiddle::TYPE_VOIDP
34
+ I = Fiddle::TYPE_INT32_T
35
+ U = Fiddle::TYPE_UINT32_T
36
+ L = Fiddle::TYPE_INT64_T
37
+ S = Fiddle::TYPE_SIZE_T
38
+ B = Fiddle::TYPE_UINT8_T
39
+ V = Fiddle::TYPE_VOID
40
+
41
+ LIMIT = struct(["uint8_t unlimited", "uint64_t value"])
42
+ GRANT_INFO = struct(["uint32_t struct_size", "int32_t kind", "int64_t issued_at",
43
+ "int64_t expires_at", "int64_t commercial_deadline"])
44
+ ANCHOR = struct(["int64_t server_time", "int64_t wall", "int64_t last_wall",
45
+ "int64_t monotonic", "int64_t last_effective", "char *boot_id"])
46
+ OBSERVATION = struct(["int64_t wall", "int64_t monotonic", "char *boot_id", "uint8_t key_present"])
47
+ MONOTONIC = struct(["char *boot_id", "int64_t monotonic_ms", "uint8_t confident"])
48
+ CLOCK = struct(["int64_t monotonic_ms", "uint8_t confident", "char boot_id[64]"])
49
+ REQUEST = struct(["char *http_method", "char *url", "char *headers", "char *body",
50
+ "size_t body_len", "uint32_t timeout_ms"])
51
+ RESPONSE = struct(["int32_t status", "char *headers", "size_t headers_cap", "size_t headers_len",
52
+ "char *body", "size_t body_cap", "size_t body_len"])
53
+ HOST = struct(["uint32_t struct_size", "void *user_data", "void *state_load", "void *state_save",
54
+ "void *state_clear", "void *key_init", "void *key_sign", "void *clock_observe", "void *http_send"])
55
+
56
+ SIGNATURES = {
57
+ abi_version: [U], status_code: [P, I],
58
+ keyset_new: [I, P, P], keyset_free: [V, P],
59
+ grant_verify: [I, P, P, P, P], grant_free: [V, P],
60
+ grant_get_info: [I, P, P], grant_claims_json: [I, P, P, S, P],
61
+ grant_has_feature: [I, P, P, L, P], grant_limit: [I, P, P, L, P],
62
+ grant_lease_kind: [I, P, P], grant_lease_expires: [I, P, P],
63
+ replay_set_new: [I, P], replay_set_free: [V, P], replay_set_insert: [I, P, P],
64
+ proof_verify: [I, P, P, P], thumbprint: [I, P, P, S, P],
65
+ proof_build: [I, P, P, P, P, P, L, P, P, P, P, S, P],
66
+ license_key_normalize: [I, P, P, S, P], trusted_now: [I, P, P, P],
67
+ receipt_time: [I, L, L, L, P, P, P],
68
+ client_new: [I, P, P, P], client_new_default: [I, P, U, P, P],
69
+ client_open_default: [I, P, P, P], client_free: [V, P],
70
+ client_activate_with_key: [I, P, P, P],
71
+ client_start_hosted_approval: [I, P, P], client_start_vendor_enrollment: [I, P, P],
72
+ client_pending_approval: [I, P, P, S, P], client_advance_approval: [I, P, P],
73
+ client_cancel_approval: [I, P], client_refresh: [I, P], client_deactivate: [I, P],
74
+ client_checkout_seat: [I, P, U], client_renew_seat: [I, P], client_release_seat: [I, P],
75
+ client_create_offline_request: [I, P, I, P, P, S, P], client_import_offline_response: [I, P, P],
76
+ client_persist: [I, P], client_has_feature: [I, P, P, P], client_feature_value: [I, P, P, P],
77
+ client_status: [I, P, P, S, P], client_last_error: [I, P, P, S, P],
78
+ license_file_verify: [I, P, P, S, P, P], license_file_free: [V, P],
79
+ license_file_claims_json: [I, P, P, S, P],
80
+ license_file_has_feature: [I, P, P, L, B, P], license_file_limit: [I, P, P, L, B, P]
81
+ }.freeze
82
+
83
+ CALLBACK_FUNCTIONS = %i[
84
+ proof_build client_new client_activate_with_key client_start_hosted_approval
85
+ client_start_vendor_enrollment client_advance_approval client_cancel_approval
86
+ client_refresh client_deactivate client_checkout_seat client_renew_seat client_release_seat
87
+ client_create_offline_request client_import_offline_response client_persist client_has_feature
88
+ client_feature_value
89
+ ].freeze
90
+
91
+ def self.windows?
92
+ Gem.win_platform?
93
+ end
94
+
95
+ def self.platform
96
+ platform = Gem::Platform.local
97
+ return platform.to_s if platform.os == "mingw32" || platform.os == "mingw"
98
+
99
+ if platform.os == "linux" && RbConfig::CONFIG.fetch("host_os").include?("musl")
100
+ return "#{platform.cpu}-linux-musl"
101
+ end
102
+ if platform.os == "linux" && RbConfig::CONFIG.fetch("host_os").include?("gnu")
103
+ return "#{platform.cpu}-linux-gnu"
104
+ end
105
+ # RubyGems also uses the unqualified x86_64-linux tag for glibc.
106
+ return "x86_64-linux-gnu" if platform.to_s == "x86_64-linux"
107
+
108
+ platform.to_s
109
+ end
110
+
111
+ def self.packaged_path
112
+ filename = windows? ? "permitplane.dll" : "libpermitplane.so"
113
+ File.expand_path("native/#{platform}/#{filename}", __dir__)
114
+ end
115
+
116
+ def self.absolute_path(path)
117
+ value = text(path)
118
+ pattern = windows? ? %r{\A(?:[A-Za-z]:[/\\]|[/\\]{2}[^/\\]+[/\\][^/\\]+)} : %r{\A/}
119
+ raise ArgumentError, "an absolute path is required" unless value.match?(pattern)
120
+
121
+ value
122
+ end
123
+
124
+ def initialize(path = nil, callbacks: false)
125
+ raise LoadError, "PermitPlane requires MRI Ruby" unless RUBY_ENGINE == "ruby"
126
+
127
+ path = self.class.absolute_path(path || self.class.packaged_path)
128
+ raise LoadError, "PermitPlane native library is missing at #{path}" unless File.file?(path)
129
+
130
+ @callbacks = callbacks
131
+ @library = if self.class.windows?
132
+ WindowsLibrary.open(File.realpath(path))
133
+ else
134
+ Fiddle::Handle.new(path, Fiddle::RTLD_NOW).tap(&:enable_close)
135
+ end
136
+ @functions = { abi_version: bind(:abi_version, SIGNATURES.fetch(:abi_version)) }
137
+ version = call(:abi_version)
138
+ raise LoadError, "PermitPlane ABI #{ABI} required, found #{version}" unless version == ABI
139
+
140
+ SIGNATURES.each { |name, signature| @functions[name] ||= bind(name, signature) }
141
+ @functions.freeze
142
+ rescue Fiddle::DLError => e
143
+ raise LoadError, "Could not load the PermitPlane native ABI: #{e.message}"
144
+ end
145
+
146
+ def call(name, *args)
147
+ @functions.fetch(name).call(*args)
148
+ end
149
+
150
+ def check(status, details = nil)
151
+ return if status.zero?
152
+
153
+ code = call(:status_code, status).to_s
154
+ raise Error.new(status, code, details)
155
+ end
156
+
157
+ def handle(name, *args)
158
+ out = self.class.buffer(Fiddle::SIZEOF_VOIDP)
159
+ out[0, Fiddle::SIZEOF_VOIDP] = [0].pack("J")
160
+ check(call(name, *args, out))
161
+ pointer = Fiddle::Pointer.new(out[0, Fiddle::SIZEOF_VOIDP].unpack1("J"))
162
+ raise LoadError, "native function returned a null handle" if pointer.null?
163
+
164
+ pointer
165
+ end
166
+
167
+ def output(name, *args, capacity: nil)
168
+ length = self.class.buffer(Fiddle::SIZEOF_SIZE_T)
169
+ length[0, Fiddle::SIZEOF_SIZE_T] = [0].pack("J")
170
+ if capacity.nil?
171
+ result = call(name, *args, nil, 0, length)
172
+ check(result) unless result == BUFFER_TOO_SMALL
173
+ raise LoadError, "native output had no size" unless result == BUFFER_TOO_SMALL
174
+ capacity = read_size(length) + 1
175
+ end
176
+ raise LoadError, "native output exceeds the buffer limit" unless capacity.between?(1, MAX_BYTES + 1)
177
+
178
+ buffer = self.class.buffer(capacity)
179
+ check(call(name, *args, buffer, capacity, length))
180
+ size = read_size(length)
181
+ raise LoadError, "native output exceeded its buffer" unless size < capacity && buffer[size, 1] == "\0"
182
+
183
+ self.class.text(buffer[0, size])
184
+ end
185
+
186
+ def scalar(name, *args, format:)
187
+ out = self.class.buffer([0].pack(format).bytesize)
188
+ check(call(name, *args, out))
189
+ out[0, out.size].unpack1(format)
190
+ end
191
+
192
+ def limit(name, *args)
193
+ out = LIMIT.malloc(Fiddle::RUBY_FREE)
194
+ check(call(name, *args, out))
195
+ { unlimited: out.unlimited == 1, value: out.value }
196
+ end
197
+
198
+ def self.buffer(size)
199
+ Fiddle::Pointer.malloc(size, Fiddle::RUBY_FREE)
200
+ end
201
+
202
+ def self.text(value, max: MAX_BYTES)
203
+ raise ArgumentError, "a string is required" unless value.is_a?(String)
204
+
205
+ str = value.encoding == Encoding::BINARY ? value.dup.force_encoding(Encoding::UTF_8) : value.encode(Encoding::UTF_8)
206
+ unless str.valid_encoding? && !str.include?("\0") && str.bytesize <= max
207
+ raise ArgumentError, "expected UTF-8 text without NUL within #{max} bytes"
208
+ end
209
+ str.dup.freeze
210
+ rescue EncodingError
211
+ raise ArgumentError, "expected valid UTF-8 text"
212
+ end
213
+
214
+ def self.bytes(value, length)
215
+ unless value.is_a?(String) && value.bytesize == length
216
+ raise ArgumentError, "expected #{length} bytes"
217
+ end
218
+ value.b.freeze
219
+ end
220
+
221
+ def self.optional_text(value)
222
+ text(value) unless value.nil?
223
+ end
224
+
225
+ def self.json(value)
226
+ text(value.is_a?(String) ? value : JSON.generate(value))
227
+ end
228
+
229
+ def self.integer(value, range = (-(1 << 63)...(1 << 63)))
230
+ raise ArgumentError, "integer is out of range" unless value.is_a?(Integer) && range.cover?(value)
231
+
232
+ value
233
+ end
234
+
235
+ def self.boolean(value)
236
+ return 1 if value.equal?(true)
237
+ return 0 if value.equal?(false)
238
+
239
+ raise ArgumentError, "expected true or false"
240
+ end
241
+
242
+ def self.callback(parameters, &operation)
243
+ Fiddle::Closure::BlockCaller.new(I, parameters) do |_, *args|
244
+ thread = Thread.current
245
+ previous = thread.thread_variable_get(CALLBACK_THREAD)
246
+ begin
247
+ thread.thread_variable_set(CALLBACK_THREAD, true)
248
+ operation.call(*args)
249
+ ensure
250
+ thread.thread_variable_set(CALLBACK_THREAD, previous)
251
+ end
252
+ rescue Exception # No Ruby exception may unwind across native frames.
253
+ 107
254
+ end
255
+ end
256
+
257
+ def self.invoke_host(&operation)
258
+ # Isolate Ruby nonlocal exits. The fiber sees only Ruby-owned inputs
259
+ # and never owns any code that accesses the native callback buffers.
260
+ fiber = Fiber.new(&operation)
261
+ result = fiber.resume
262
+ raise FiberError, "the host callback yielded" if fiber.alive?
263
+
264
+ result
265
+ end
266
+
267
+ private
268
+
269
+ def bind(name, signature)
270
+ result, *args = signature
271
+ need_gvl = name == :proof_build || (@callbacks && CALLBACK_FUNCTIONS.include?(name))
272
+ Fiddle::Function.new(@library["pp_#{name}"], args, result, need_gvl: need_gvl)
273
+ end
274
+
275
+ def read_size(pointer)
276
+ pointer[0, Fiddle::SIZEOF_SIZE_T].unpack1("J")
277
+ end
278
+
279
+ # kernel32 is a Windows KnownDLL. LoadLibraryExW restricts dependencies
280
+ # of the selected PermitPlane DLL to its own directory and System32.
281
+ class WindowsLibrary
282
+ @modules = {}
283
+ @mutex = Mutex.new
284
+
285
+ def self.open(path)
286
+ @mutex.synchronize { @modules[path] ||= new(path) }
287
+ end
288
+
289
+ def initialize(path)
290
+ @kernel32 = Fiddle::Handle.new("kernel32.dll")
291
+ wide = (path.encode(Encoding::UTF_16LE).b + "\0\0")
292
+ load = Fiddle::Function.new(@kernel32["LoadLibraryExW"], [P, P, U], P)
293
+ @module = load.call(wide, nil, 0x00000100 | 0x00000800)
294
+ raise Fiddle::DLError, "LoadLibraryExW failed for #{path}" if @module.null?
295
+
296
+ @lookup = Fiddle::Function.new(@kernel32["GetProcAddress"], [P, P], P)
297
+ end
298
+
299
+ def [](symbol)
300
+ address = @lookup.call(@module, symbol)
301
+ raise Fiddle::DLError, "missing symbol #{symbol}" if address.null?
302
+
303
+ address.to_i
304
+ end
305
+ end
306
+ end
307
+ end