View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2014-2021, VU University Amsterdam
    7                              SWI-Prolog Solutions b.v.
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36:- module(modules,
   37          [ in_temporary_module/3,              % ?Module, :Setup, :Goal
   38            current_temporary_module/1          % ?Module
   39          ]).   40
   41
   42/** <module> Module utility predicates
   43*/
   44
   45:- meta_predicate
   46    in_temporary_module(?, 0, 0).   47
   48%!  in_temporary_module(?Module, :Setup, :Goal)
   49%
   50%   Run Goal on temporary loaded sources  and discard the module and
   51%   loaded predicates after completion.  This predicate performs the
   52%   following steps:
   53%
   54%     1. If Module is unbound, create a unique identifier for it.
   55%     2. Turn Module into a _temporary_ module using set_module/1.
   56%        Note that this requires the module to be non-existent or
   57%        empty.  If Module is specified, it should typically be set
   58%        to a unique value as obtained from e.g. uuid/1.
   59%     3. Run Setup in the context of Module.
   60%     4. If setup succeeded possible choice points are discarded
   61%        and Goal is started.
   62%
   63%   The  logical  result  of  this   predicate    is   the  same  as
   64%   `(Setup@Module -> Goal@Module)`, i.e., both   Setup and Goal are
   65%   resolved relative to the current  module,   but  executed in the
   66%   context of Module.  If  Goal  must   be  called  in  Module, use
   67%   `call(Goal)`.
   68%
   69%   The module and all  its  predicates   are  destroyed  after Goal
   70%   terminates, as defined by setup_call_cleanup/3.
   71%
   72%   *Discussion* This predicate is intended to   load programs in an
   73%   isolated   environment   and   reclaim   all   resources.   This
   74%   unfortunately is incomplete:
   75%
   76%     - Running the code may leave side effects such as creating
   77%       records, flags, changing Prolog flags, etc.  The system
   78%       has no provisions to track this.
   79%     - So called _functors_ (name/arity pairs) are not yet subject
   80%       to garbage collection.  Functors are both used to define
   81%       predicates and to create compound terms.
   82%
   83%   @see    library(sandbox) determines whether unknown goals are safe
   84%           to call.
   85%   @see    load_files/2 offers the option sandboxed(true) to load code
   86%           from unknown sources safely.
   87
   88in_temporary_module(Module, Setup, Goal) :-
   89    setup_call_cleanup(
   90        prepare_temporary_module(Module),
   91        (   @(Setup, Module)
   92        ->  @(Goal,  Module)
   93        ),
   94        destroy_module(Module)).
   95
   96prepare_temporary_module(Module) :-
   97    var(Module),
   98    !,
   99    (   thread_id(Tid),
  100        repeat,
  101        I is random(1<<62),
  102        atomic_list_concat([tmp, Tid, I], -, Module),
  103        catch(set_module(Module:class(temporary)),
  104              error(permission_error(_,_,_),_), fail)
  105    ->  b_setval('$tmp_module', Module)
  106    ).
  107prepare_temporary_module(Module) :-
  108    set_module(Module:class(temporary)),
  109    b_setval('$tmp_module', Module).
  110
  111:- if(current_prolog_flag(threads, true)).  112thread_id(Id) :-
  113    thread_self(Self),
  114    thread_property(Self, id(Id)).
  115:- else.  116thread_id(main).
  117:- endif.  118
  119destroy_module(Module) :-
  120    retractall(system:'$load_context_module'(_File, Module, _Options)),
  121    '$destroy_module'(Module).
  122
  123%!  current_temporary_module(-Module) is semidet.
  124%
  125%   True when we are executing in the given temporary module context.
  126
  127current_temporary_module(Module) :-
  128    nb_current('$tmp_module', Module)