summaryrefslogtreecommitdiff
path: root/chrome/content/ctypes-utils.js
blob: 9fd24ece909e1893257abd6fbfe129b14b18537a (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
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
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 *	 Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Firetray
 *
 * The Initial Developer of the Original Code is
 * Mozilla Messaging, Ltd.
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *    Chris Coulson <chris.coulson@canonical.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

const Cu = Components.utils;

Cu.import("resource://gre/modules/ctypes.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("chrome://topmenu/content/log4moz.js");

var EXPORTED_SYMBOLS  = [ "ctypes_library" ];

let log = Log4Moz.repository.getLogger("topmenu.ctypes-utils");

/**
 * Loads a library using ctypes and exports an object on to the specified
 * global object. The name of the exported object will be the first name
 * specified in the global objects EXPORTED_SYMBOLS list.
 *
 * It is an error to call this function more than once in a JS module. This
 * implies that you should have one JS module per ctypes library.
 *
 * In addition to native types and functions, the exported object will contain
 * some additional utility functions:
 *
 * close      Close the library and unload the JS module
 * available  Returns true if the library is available, false otherwise
 * ABI        A property containing the library ABI loaded (or -1 if unavailable)
 *
 * @param  aName
 *         The name of the library to load, without the "lib" prefix or any
 *         file extension.
 *
 * @param  aABIs
 *         An array of library ABI's to search for. The first one found will
 *         be loaded and the loaded ABI will be saved on the exported object.
 *
 * @param  aDefines
 *         A function which will be called to load library symbols and create
 *         types. The function will be called with one parameter, which contains
 *         several functions for binding symbols. The "this" object will be
 *         the exported object, on to which you can should types and symbols.
 *
 * @param  aGlobal
 *         The global object on to which we export an object. This must be a
 *         a valid JSM global object.
 *
 */
function ctypes_library(aName, aABIs, aDefines, aGlobal) {
  try {
    log.debug("Trying to load library: " + aName);

    if (typeof(aName) != "string") {
      throw Error("Invalid library name");
    }

    if (!aABIs || typeof(aABIs) != "object") {
      throw Error("Invalid range of library ABI's");
    }

    if (typeof(aDefines) != "function") {
      throw Error("Invalid defines function");
    }

    if (!aGlobal || typeof(aGlobal) != "object" || !aGlobal.EXPORTED_SYMBOLS ||
        typeof(aGlobal.EXPORTED_SYMBOLS) != "object") {
      throw Error("Must specify a valid global object from a loaded JS module");
    }

    if (!("__URI__" in aGlobal) || !aGlobal.__URI__) {
      throw Error("This JS module has already been unloaded");
    }

    if (aGlobal[aGlobal.EXPORTED_SYMBOLS[0]]) {
      throw Error("Was ctypes_library() called more than once for this module?");
    }

    var library;
    for each (let abi in aABIs) {
      let soname = "lib" + aName + ".so." + abi.toString();
      log.debug("Trying " + soname);
      try {
        library = ctypes.open(soname);
        this.ABI = abi;
        log.debug("Successfully loaded " + soname);
        break;
      } catch(e) {
          log.error(soname+" unfound.");
      }
    }

    this.name = aName;

    this.close = function() {
      log.debug("Closing library " + aName);
      library.close();
      this.ABI = -1;

      if (!("__URI__" in aGlobal) || !aGlobal.__URI__) {
        // We could have already been unloaded by now
        return;
      }

      log.debug("Unloading JS module " + aGlobal.__URI__);
      Cu.unload(aGlobal.__URI__);
    };

    this.available = function() {
      return this.ABI != -1;
    };

    if (!library) {
      log.debug("Failed to load library: " + aName);
      this.ABI = -1;
      return;
    }

    var self = this;
    let lib = {
      declare: function() {
        try {
          args = [];
          args.push(arguments[0]);
          args.push(ctypes.default_abi);
          for each (let arg in Array.prototype.slice.call(arguments, 1)) {
            args.push(arg);
          }

          return library.declare.apply(library, args);
        } catch (ex) {
          Cu.reportError(ex);
          log.error("Missing symbol " + arguments[0] + " in library " + aName);
          self.ABI = -1;
          return null;
        }
      },

      lazy_bind: function() {
        var args = Array.prototype.slice.call(arguments, 0);
        XPCOMUtils.defineLazyGetter(self, arguments[0], function() {
          return lib.declare.apply(lib, args);
        });
      },

      bind_now: function() {
        self[arguments[0]] = this.declare.apply(this, arguments);
      }
    };

    aDefines.call(this, lib);

    aGlobal[aGlobal.EXPORTED_SYMBOLS[0]] = this;
  } catch(e) {
    Cu.reportError(e);
    log.error(aName+" definition error: "+e);
    this.ABI = -1;
  }
}