summaryrefslogtreecommitdiff
path: root/xmake/core/sandbox/sandbox.lua
blob: 64729bf7f26706860be208b5ca0437c0ab30e7f9 (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
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
--!The Automatic Cross-platform Build Tool
-- 
-- XMake is free software; you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation; either version 2.1 of the License, or
-- (at your option) any later version.
-- 
-- XMake is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU Lesser General Public License for more details.
-- 
-- You should have received a copy of the GNU Lesser General Public License
-- along with XMake; 
-- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a>
-- 
-- Copyright (C) 2015 - 2016, ruki All rights reserved.
--
-- @author      ruki
-- @file        sandbox.lua
--

-- define module
local sandbox = sandbox or {}

-- load modules
local os        = require("base/os")
local path      = require("base/path")
local table     = require("base/table")
local utils     = require("base/utils")
local string    = require("base/string")
local option    = require("base/option")

-- traceback
function sandbox._traceback(errors)

    -- not verbose?
    if not option.get("backtrace") then
        if errors then
            -- remove the prefix info
            local _, pos = errors:find(":%d+: ")
            if pos then
                return errors:sub(pos + 1)
            end
        end
        return errors
    end

    -- init results
    local results = ""
    if errors then
        results = errors .. "\n"
    end
    results = results .. "stack traceback:\n"

    -- make results
    local level = 2    
    while true do    

        -- get debug info
        local info = debug.getinfo(level, "Sln")

        -- end?
        if not info then
            break
        end

        -- function?
        if info.what == "C" then
            results = results .. string.format("    [C]: in function '%s'\n", info.name)
        elseif info.name then 
            results = results .. string.format("    [%s:%d]: in function '%s'\n", info.short_src, info.currentline, info.name)    
        elseif info.what == "main" then
            results = results .. string.format("    [%s:%d]: in main chunk\n", info.short_src, info.currentline)    
            break
        else
            results = results .. string.format("    [%s:%d]:\n", info.short_src, info.currentline)    
        end

        -- next
        level = level + 1    
    end    

    -- ok?
    return results
end

-- register api for builtin
function sandbox._api_register_builtin(self, name, func)

    -- check
    assert(self and self._PUBLIC and func)

    -- register it
    self._PUBLIC[name] = func
end

-- new a sandbox instance
function sandbox._new()

    -- init an sandbox instance
    local instance = {_PUBLIC = {}, _PRIVATE = {}}

    -- inherit the interfaces of sandbox
    table.inherit2(instance, sandbox)

    -- load builtin module files
    local builtin_module_files = os.match(path.join(xmake._CORE_DIR, "sandbox/modules/*.lua"))
    if builtin_module_files then
        for _, builtin_module_file in ipairs(builtin_module_files) do

            -- the module name
            local module_name = path.basename(builtin_module_file)
            assert(module_name)

            -- load script
            local script, errors = loadfile(builtin_module_file)
            if script then

                -- load module
                local ok, results = xpcall(script, debug.traceback)
                if not ok then
                    os.raise(results)
                end

                -- register module
                instance:_api_register_builtin(module_name, results)
            else
                -- error
                os.raise(errors)
            end
        end
    end

    -- save instance
    setmetatable(instance._PUBLIC, {    __index = function (tbl, key)
                                        if type(key) == "string" and key == "_SANDBOX" and rawget(tbl, "_SANDBOX_READABLE") then
                                            return instance
                                        end
                                        return rawget(tbl, key)
                                    end
                                ,   __newindex = function (tbl, key, val)
                                        if type(key) == "string" and (key == "_SANDBOX" or key == "_SANDBOX_READABLE") then
                                            return 
                                        end
                                        rawset(tbl, key, val)
                                    end}) 

    -- ok?
    return instance
end

-- new a sandbox instance with the given script
function sandbox.new(script, filter, rootdir)

    -- check
    assert(script)

    -- new instance 
    local self = sandbox._new()

    -- check
    assert(self and self._PUBLIC and self._PRIVATE)

    -- save filter
    self._PRIVATE._FILTER = filter

    -- save root directory
    self._PRIVATE._ROOTDIR = rootdir

    -- this script is module name? import it first
    if type(script) == "string" then
    
        -- import module as script
        local modulename = script
        script = function ()
       
            -- import it
            import(modulename).main()
        end
    end

    -- no script?
    if script == nil then
        return nil, "no script!"
    end

    -- invalid script?
    if script ~= nil and type(script) ~= "function" then
        return nil, "invalid script!"
    end

    -- bind public scope
    setfenv(script, self._PUBLIC)

    -- save script
    self._PRIVATE._SCRIPT = script

    -- ok
    return self
end

-- load script in the sandbox
function sandbox.load(script, ...)

    -- load script
    return xpcall(script, sandbox._traceback, ...)
end

-- fork a new sandbox from the given sandbox
function sandbox:fork(script)

    -- no script?
    if script == nil then
        return nil, "no script!"
    end

    -- invalid script?
    if script ~= nil and type(script) ~= "function" then
        return nil, "invalid script!"
    end

    -- init a new sandbox instance
    local instance = sandbox._new()

    -- check
    assert(instance and instance._PUBLIC and instance._PRIVATE)

    -- inherit the filter
    instance._PRIVATE._FILTER = self:filter()

    -- inherit the root directory
    instance._PRIVATE._ROOTDIR = self:rootdir()

    -- bind public scope
    setfenv(script, instance._PUBLIC)

    -- save script
    instance._PRIVATE._SCRIPT = script

    -- ok?
    return instance
end

-- load script and import module 
function sandbox:import()

    -- this module has been imported?
    if self._PRIVATE._MODULE then
        return self._PRIVATE._MODULE
    end

    -- backup the scope variables first
    local scope_public = getfenv(self:script())
    local scope_backup = {}
    table.copy2(scope_backup, scope_public)

    -- load module with sandbox
    local ok, errors = sandbox.load(self:script())
    if not ok then
        return nil, errors
    end

    -- only export new public functions
    local module = {}
    for k, v in pairs(scope_public) do
        if type(v) == "function" and not k:startswith("_") and scope_backup[k] == nil then
            module[k] = v
        end
    end

    -- save module
    self._PRIVATE._MODULE = module

    -- ok
    return module

end

-- get script from the given sandbox
function sandbox:script()

    -- check
    assert(self and self._PRIVATE)

    -- get it
    return self._PRIVATE._SCRIPT
end

-- get filter from the given sandbox
function sandbox:filter()

    -- check
    assert(self and self._PRIVATE)

    -- get it
    return self._PRIVATE._FILTER
end

-- get root directory from the given sandbox
function sandbox:rootdir()

    -- check
    assert(self and self._PRIVATE)

    -- get it
    return self._PRIVATE._ROOTDIR
end

-- get current instance in the sandbox modules
function sandbox.instance()

    -- find self instance for the current sandbox
    local instance = nil
    local level = 2
    while level < 16 do

        -- get scope
        local scope = getfenv(level)
        if scope then

            -- enable to read _SANDBOX
            rawset(scope, "_SANDBOX_READABLE", true)
            
            -- attempt to get it
            instance = scope._SANDBOX

            -- disable to read _SANDBOX
            rawset(scope, "_SANDBOX_READABLE", nil)
        end

        -- found?
        if instance then
            break
        end

        -- next
        level = level + 1
    end

    -- ok?
    return instance 
end

-- return module
return sandbox