This repository has been archived by the owner on Jan 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
lib.js
81 lines (72 loc) · 2.61 KB
/
lib.js
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
// Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under
// the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT> or
// the Modified BSD license <LICENSE-BSD or https://opensource.org/licenses/BSD-3-Clause>,
// at your option.
//
// This file may not be copied, modified, or distributed except according to those terms.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
const path = require('path');
const fs = require('fs');
const FFI = require('ffi');
const { getSafeAppLibFilename } = require('../helpers');
const { getSystemUriLibFilename } = require('../helpers');
const os = require('os');
const currentDir = path.dirname(__filename);
const api = require('./api');
const makeError = require('./_error.js');
const errConst = require('./../error_const');
const ffi = {};
const RTLD_NOW = FFI.DynamicLibrary.FLAGS.RTLD_NOW;
const RTLD_GLOBAL = FFI.DynamicLibrary.FLAGS.RTLD_GLOBAL;
const mode = RTLD_NOW | RTLD_GLOBAL;
let lib = null;
ffi.init = (options) => {
try {
lib = FFI.DynamicLibrary(getSafeAppLibFilename(currentDir, options), mode);
api.forEach((mod) => {
if (!lib) {
throw new Error('Native library not initialised');
}
if (mod.functions){
for (const key in mod.functions) {
const funcDefinition = mod.functions[key];
ffi[key] = FFI.ForeignFunction(lib.get(key),
funcDefinition[0],
funcDefinition[1])
}
}
if (mod.api) {
for (const key in mod.api) {
ffi[key].fn_name = key;
let fn = mod.api[key](ffi, ffi[key]);
fn.fn_name = "[mapped]" + key;
ffi[key] = fn;
}
// Object.assign(mappings, mod.api);
}
if (mod.helpersForNative) {
for (const key in mod.helpersForNative) {
let fn = mod.helpersForNative[key];
fn.fn_name = "[mapped]" + key;
ffi[key] = fn;
}
}
});
// FIXME: As long as `safe-app` doesn't expose system uri itself, we'll
// patch it directly on it. This should later move into its own sub-module
// and take care of mobile support for other platforms, too.
const mobileEnv = !fs.existsSync(getSystemUriLibFilename(currentDir));
if (!mobileEnv) {
require('./_system_uri')(ffi, options);
}
} catch(e) {
console.error(e)
throw makeError(errConst.FAILED_TO_LOAD_LIB.code,
errConst.FAILED_TO_LOAD_LIB.msg(e.toString()));
}
};
module.exports = ffi;