webrtc-sys 0.3.34

Unsafe bindings to libwebrtc
Documentation
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/*
 * Copyright 2018-2025 Yury Gribov
 *
 * The MIT License (MIT)
 *
 * Use of this source code is governed by MIT license that can be
 * found in the LICENSE.txt file.
 */

#ifndef _GNU_SOURCE
#define _GNU_SOURCE // For RTLD_DEFAULT
#endif

#define HAS_DLOPEN_CALLBACK 0
#define HAS_DLSYM_CALLBACK 0
#define NO_DLOPEN 0
#define LAZY_LOAD 1
#define THREAD_SAFE 1

#include <dlfcn.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>

#if THREAD_SAFE
#include <pthread.h>
#endif

// Sanity check for ARM to avoid puzzling runtime crashes
#ifdef __arm__
# if defined __thumb__ && ! defined __THUMB_INTERWORK__
#   error "ARM trampolines need -mthumb-interwork to work in Thumb mode"
# endif
#endif

#ifdef __cplusplus
extern "C" {
#endif

#define CHECK(cond, fmt, ...) do { \
    if(!(cond)) { \
      fprintf(stderr, "implib-gen: libdrm.so.2: " fmt "\n", ##__VA_ARGS__); \
      assert(0 && "Assertion in generated code"); \
      abort(); \
    } \
  } while(0)

static void *lib_handle;
static int dlopened;

#if ! NO_DLOPEN

#if THREAD_SAFE

// We need to consider two cases:
// - different threads calling intercepted APIs in parallel
// - same thread calling 2 intercepted APIs recursively
//   due to dlopen calling library constructors
//   (usually happens only under IMPLIB_EXPORT_SHIMS)

// Current recursive mutex approach will deadlock
// if library constructor starts and joins a new thread
// which (directly or indirectly) calls another library function.
// Such situations should be very rare (although chances
// are higher when -DIMLIB_EXPORT_SHIMS are enabled).
//
// Similar issue is present in Glibc so hopefully it's
// not a big deal: // http://sourceware.org/bugzilla/show_bug.cgi?id=15686
// (also google for "dlopen deadlock).

static pthread_mutex_t mtx;
static int rec_count;

static void init_lock(void) {
  // We need recursive lock because dlopen will call library constructors
  // which may call other intercepted APIs that will call load_library again.
  // PTHREAD_RECURSIVE_MUTEX_INITIALIZER is not portable
  // so we do it hard way.

  pthread_mutexattr_t attr;
  CHECK(0 == pthread_mutexattr_init(&attr), "failed to init mutex");
  CHECK(0 == pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE), "failed to init mutex");

  CHECK(0 == pthread_mutex_init(&mtx, &attr), "failed to init mutex");
}

static int lock(void) {
  static pthread_once_t once = PTHREAD_ONCE_INIT;
  CHECK(0 == pthread_once(&once, init_lock), "failed to init lock");

  CHECK(0 == pthread_mutex_lock(&mtx), "failed to lock mutex");

  return 0 == __sync_fetch_and_add(&rec_count, 1);
}

static void unlock(void) {
  __sync_fetch_and_add(&rec_count, -1);
  CHECK(0 == pthread_mutex_unlock(&mtx), "failed to unlock mutex");
}
#else
static int lock(void) {
  return 1;
}
static void unlock(void) {}
#endif

static int load_library(void) {
  int publish = lock();

  if (lib_handle) {
    unlock();
    return publish;
  }

#if HAS_DLOPEN_CALLBACK
  extern void *(const char *lib_name);
  lib_handle = ("libdrm.so.2");
  CHECK(lib_handle, "failed to load library 'libdrm.so.2' via callback ''");
#else
  lib_handle = dlopen("libdrm.so.2", RTLD_LAZY | RTLD_GLOBAL);
  CHECK(lib_handle, "failed to load library 'libdrm.so.2' via dlopen: %s", dlerror());
#endif

  // With (non-default) IMPLIB_EXPORT_SHIMS we may call dlopen more than once
  // so dlclose it if we are not the first ones
  if (__sync_val_compare_and_swap(&dlopened, 0, 1)) {
    dlclose(lib_handle);
  }

  unlock();

  return publish;
}

// Run dtor as late as possible in case library functions are
// called in other global dtors
// FIXME: this may crash if one thread is calling into library
// while some other thread executes exit(). It's no clear
// how to fix this besides simply NOT dlclosing library at all.
static void __attribute__((destructor(101))) unload_lib(void) {
  if (dlopened) {
    dlclose(lib_handle);
    lib_handle = 0;
    dlopened = 0;
  }
}
#endif

#if ! NO_DLOPEN && ! LAZY_LOAD
static void __attribute__((constructor(101))) load_lib(void) {
  load_library();
}
#endif

// TODO: convert to single 0-separated string
static const char *const sym_names[] = {
  "drmAddBufs",
  "drmAddContextPrivateMapping",
  "drmAddContextTag",
  "drmAddMap",
  "drmAgpAcquire",
  "drmAgpAlloc",
  "drmAgpBase",
  "drmAgpBind",
  "drmAgpDeviceId",
  "drmAgpEnable",
  "drmAgpFree",
  "drmAgpGetMode",
  "drmAgpMemoryAvail",
  "drmAgpMemoryUsed",
  "drmAgpRelease",
  "drmAgpSize",
  "drmAgpUnbind",
  "drmAgpVendorId",
  "drmAgpVersionMajor",
  "drmAgpVersionMinor",
  "drmAuthMagic",
  "drmAvailable",
  "drmCheckModesettingSupported",
  "drmClose",
  "drmCloseBufferHandle",
  "drmCloseOnce",
  "drmCommandNone",
  "drmCommandRead",
  "drmCommandWrite",
  "drmCommandWriteRead",
  "drmCreateContext",
  "drmCreateDrawable",
  "drmCrtcGetSequence",
  "drmCrtcQueueSequence",
  "drmCtlInstHandler",
  "drmCtlUninstHandler",
  "drmDMA",
  "drmDelContextTag",
  "drmDestroyContext",
  "drmDestroyDrawable",
  "drmDevicesEqual",
  "drmDropMaster",
  "drmError",
  "drmFinish",
  "drmFree",
  "drmFreeBufs",
  "drmFreeBusid",
  "drmFreeDevice",
  "drmFreeDevices",
  "drmFreeReservedContextList",
  "drmFreeVersion",
  "drmGetBufInfo",
  "drmGetBusid",
  "drmGetCap",
  "drmGetClient",
  "drmGetContextFlags",
  "drmGetContextPrivateMapping",
  "drmGetContextTag",
  "drmGetDevice",
  "drmGetDevice2",
  "drmGetDeviceFromDevId",
  "drmGetDeviceNameFromFd",
  "drmGetDeviceNameFromFd2",
  "drmGetDevices",
  "drmGetDevices2",
  "drmGetEntry",
  "drmGetFormatModifierName",
  "drmGetFormatModifierVendor",
  "drmGetFormatName",
  "drmGetHashTable",
  "drmGetInterruptFromBusID",
  "drmGetLibVersion",
  "drmGetLock",
  "drmGetMagic",
  "drmGetMap",
  "drmGetNodeTypeFromDevId",
  "drmGetNodeTypeFromFd",
  "drmGetPrimaryDeviceNameFromFd",
  "drmGetRenderDeviceNameFromFd",
  "drmGetReservedContextList",
  "drmGetStats",
  "drmGetVersion",
  "drmHandleEvent",
  "drmHashCreate",
  "drmHashDelete",
  "drmHashDestroy",
  "drmHashFirst",
  "drmHashInsert",
  "drmHashLookup",
  "drmHashNext",
  "drmIoctl",
  "drmIsKMS",
  "drmIsMaster",
  "drmMalloc",
  "drmMap",
  "drmMapBufs",
  "drmMarkBufs",
  "drmModeAddFB",
  "drmModeAddFB2",
  "drmModeAddFB2WithModifiers",
  "drmModeAtomicAddProperty",
  "drmModeAtomicAlloc",
  "drmModeAtomicCommit",
  "drmModeAtomicDuplicate",
  "drmModeAtomicFree",
  "drmModeAtomicGetCursor",
  "drmModeAtomicMerge",
  "drmModeAtomicSetCursor",
  "drmModeAttachMode",
  "drmModeCloseFB",
  "drmModeConnectorGetPossibleCrtcs",
  "drmModeConnectorSetProperty",
  "drmModeCreateDumbBuffer",
  "drmModeCreateLease",
  "drmModeCreatePropertyBlob",
  "drmModeCrtcGetGamma",
  "drmModeCrtcSetGamma",
  "drmModeDestroyDumbBuffer",
  "drmModeDestroyPropertyBlob",
  "drmModeDetachMode",
  "drmModeDirtyFB",
  "drmModeFormatModifierBlobIterNext",
  "drmModeFreeConnector",
  "drmModeFreeCrtc",
  "drmModeFreeEncoder",
  "drmModeFreeFB",
  "drmModeFreeFB2",
  "drmModeFreeModeInfo",
  "drmModeFreeObjectProperties",
  "drmModeFreePlane",
  "drmModeFreePlaneResources",
  "drmModeFreeProperty",
  "drmModeFreePropertyBlob",
  "drmModeFreeResources",
  "drmModeGetConnector",
  "drmModeGetConnectorCurrent",
  "drmModeGetConnectorTypeName",
  "drmModeGetCrtc",
  "drmModeGetEncoder",
  "drmModeGetFB",
  "drmModeGetFB2",
  "drmModeGetLease",
  "drmModeGetPlane",
  "drmModeGetPlaneResources",
  "drmModeGetProperty",
  "drmModeGetPropertyBlob",
  "drmModeGetResources",
  "drmModeListLessees",
  "drmModeMapDumbBuffer",
  "drmModeMoveCursor",
  "drmModeObjectGetProperties",
  "drmModeObjectSetProperty",
  "drmModePageFlip",
  "drmModePageFlipTarget",
  "drmModeRevokeLease",
  "drmModeRmFB",
  "drmModeSetCrtc",
  "drmModeSetCursor",
  "drmModeSetCursor2",
  "drmModeSetPlane",
  "drmMsg",
  "drmOpen",
  "drmOpenControl",
  "drmOpenOnce",
  "drmOpenOnceWithType",
  "drmOpenRender",
  "drmOpenWithType",
  "drmPrimeFDToHandle",
  "drmPrimeHandleToFD",
  "drmRandom",
  "drmRandomCreate",
  "drmRandomDestroy",
  "drmRandomDouble",
  "drmRmMap",
  "drmSLCreate",
  "drmSLDelete",
  "drmSLDestroy",
  "drmSLDump",
  "drmSLFirst",
  "drmSLInsert",
  "drmSLLookup",
  "drmSLLookupNeighbors",
  "drmSLNext",
  "drmScatterGatherAlloc",
  "drmScatterGatherFree",
  "drmSetBusid",
  "drmSetClientCap",
  "drmSetContextFlags",
  "drmSetInterfaceVersion",
  "drmSetMaster",
  "drmSetServerInfo",
  "drmSwitchToContext",
  "drmSyncobjCreate",
  "drmSyncobjDestroy",
  "drmSyncobjEventfd",
  "drmSyncobjExportSyncFile",
  "drmSyncobjFDToHandle",
  "drmSyncobjHandleToFD",
  "drmSyncobjImportSyncFile",
  "drmSyncobjQuery",
  "drmSyncobjQuery2",
  "drmSyncobjReset",
  "drmSyncobjSignal",
  "drmSyncobjTimelineSignal",
  "drmSyncobjTimelineWait",
  "drmSyncobjTransfer",
  "drmSyncobjWait",
  "drmUnlock",
  "drmUnmap",
  "drmUnmapBufs",
  "drmUpdateDrawableInfo",
  "drmWaitVBlank",
  0
};

#define SYM_COUNT (sizeof(sym_names)/sizeof(sym_names[0]) - 1)

extern void *_libdrm_so_tramp_table[];

// Can be sped up by manually parsing library symtab...
void *_libdrm_so_tramp_resolve(size_t i) {
  assert(i < SYM_COUNT);

  int publish = 1;

  void *h = 0;
#if NO_DLOPEN
  // Library with implementations must have already been loaded.
  if (lib_handle) {
    // User has specified loaded library
    h = lib_handle;
  } else {
    // User hasn't provided us the loaded library so search the global namespace.
#   ifndef IMPLIB_EXPORT_SHIMS
    // If shim symbols are hidden we should search
    // for first available definition of symbol in library list
    h = RTLD_DEFAULT;
#   else
    // Otherwise look for next available definition
    h = RTLD_NEXT;
#   endif
  }
#else
  publish = load_library();
  h = lib_handle;
  CHECK(h, "failed to resolve symbol '%s', library failed to load", sym_names[i]);
#endif

  void *addr;
#if HAS_DLSYM_CALLBACK
  extern void *(void *handle, const char *sym_name);
  addr = (h, sym_names[i]);
  CHECK(addr, "failed to resolve symbol '%s' via callback ", sym_names[i]);
#else
  // Dlsym is thread-safe so don't need to protect it.
  addr = dlsym(h, sym_names[i]);
  CHECK(addr, "failed to resolve symbol '%s' via dlsym: %s", sym_names[i], dlerror());
#endif

  if (publish) {
    // Use atomic to please Tsan and ensure that preceeding writes
    // in library ctors have been delivered before publishing address
    (void)__sync_val_compare_and_swap(&_libdrm_so_tramp_table[i], 0, addr);
  }

  return addr;
}

// Below APIs are not thread-safe
// and it's not clear how make them such
// (we can not know if some other thread is
// currently executing library code).

// Helper for user to resolve all symbols
void _libdrm_so_tramp_resolve_all(void) {
  size_t i;
  for(i = 0; i < SYM_COUNT; ++i)
    _libdrm_so_tramp_resolve(i);
}

// Allows user to specify manually loaded implementation library.
void _libdrm_so_tramp_set_handle(void *handle) {
  // TODO: call unload_lib ?
  lib_handle = handle;
  dlopened = 0;
}

// Resets all resolved symbols. This is needed in case
// client code wants to reload interposed library multiple times.
void _libdrm_so_tramp_reset(void) {
  // TODO: call unload_lib ?
  memset(_libdrm_so_tramp_table, 0, SYM_COUNT * sizeof(_libdrm_so_tramp_table[0]));
  lib_handle = 0;
  dlopened = 0;
}

#ifdef __cplusplus
}  // extern "C"
#endif