summaryrefslogtreecommitdiffstats
path: root/comm/chat/modules/CLib.sys.mjs
blob: 35226b565bec11d238105f1d8d0c6d65ce264adf (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import { ctypes } from "resource://gre/modules/ctypes.sys.mjs";

var OS = Services.appinfo.OS.toLowerCase();

// type defs

var FILE = ctypes.StructType("FILE");
var fname_t = ctypes.char.ptr;
var wchar_t = ctypes.char16_t;

// Set the abi and path to CLib based on the OS.
var libcAbi, libcPath;
var strdup = "strdup";
var fopen = "fopen";

switch (OS) {
  case "win32":
  case "winnt":
    libcAbi = ctypes.winapi_abi;
    libcPath = ctypes.libraryName("msvcrt");
    strdup = "_strdup";
    fopen = "_wfopen";
    fname_t = wchar_t.ptr;
    break;
  case "darwin":
  case "dragonfly":
  case "netbsd":
  case "openbsd":
    libcAbi = ctypes.default_abi;
    libcPath = ctypes.libraryName("c");
    break;
  case "freebsd":
    libcAbi = ctypes.default_abi;
    libcPath = "libc.so.7";
    break;
  case "linux":
    libcAbi = ctypes.default_abi;
    libcPath = "libc.so.6";
    break;
  default:
    throw new Error("Unknown OS");
}

var libc = ctypes.open(libcPath);

export var CLib = {
  FILE,
  memcmp: libc.declare(
    "memcmp",
    libcAbi,
    ctypes.int,
    ctypes.void_t.ptr,
    ctypes.void_t.ptr,
    ctypes.size_t
  ),
  free: libc.declare("free", libcAbi, ctypes.void_t, ctypes.void_t.ptr),
  strdup: libc.declare(strdup, libcAbi, ctypes.char.ptr, ctypes.char.ptr),
  fclose: libc.declare("fclose", libcAbi, ctypes.int, FILE.ptr),
  fopen: libc.declare(fopen, libcAbi, FILE.ptr, fname_t, fname_t),
};