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)  2013-2020, VU University Amsterdam
    7                              CWI, Amsterdam
    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(sandbox,
   37          [ safe_goal/1,                % :Goal
   38            safe_call/1                 % :Goal
   39          ]).   40:- use_module(library(apply_macros),[expand_phrase/2]).   41:- use_module(library(apply),[maplist/2]).   42:- use_module(library(assoc),[empty_assoc/1,get_assoc/3,put_assoc/4]).   43:- use_module(library(debug),[debug/3,debugging/1]).   44:- use_module(library(error),
   45              [ must_be/2,
   46                instantiation_error/1,
   47                type_error/2,
   48                permission_error/3
   49              ]).   50:- use_module(library(lists),[append/3]).   51:- use_module(library(prolog_format),[format_types/2]).   52
   53:- multifile
   54    safe_primitive/1,               % Goal
   55    safe_meta_predicate/1,          % Name/Arity
   56    safe_meta/2,                    % Goal, Calls
   57    safe_meta/3,                    % Goal, Context, Calls
   58    safe_global_variable/1,         % Name
   59    safe_directive/1.               % Module:Goal
   60
   61% :- debug(sandbox).
   62
   63/** <module> Sandboxed Prolog code
   64
   65Prolog is a full-featured Turing complete  programming language in which
   66it is easy to write programs that can   harm your computer. On the other
   67hand, Prolog is a logic based _query language_ which can be exploited to
   68query data interactively from, e.g.,  the   web.  This  library provides
   69safe_goal/1, which determines whether it is safe to call its argument.
   70
   71@tbd    Handling of ^ and // meta predicates
   72@tbd    Complete set of whitelisted predicates
   73@see    http://www.swi-prolog.org/pldoc/package/pengines.html
   74*/
   75
   76
   77:- meta_predicate
   78    safe_goal(:),
   79    safe_call(0).   80
   81%!  safe_call(:Goal)
   82%
   83%   Call Goal if it  complies  with   the  sandboxing  rules. Before
   84%   calling   Goal,   it   performs   expand_goal/2,   followed   by
   85%   safe_goal/1. Expanding is done explicitly  because situations in
   86%   which safe_call/1 typically concern goals that  are not known at
   87%   compile time.
   88%
   89%   @see safe_goal/1.
   90
   91safe_call(Goal0) :-
   92    expand_goal(Goal0, Goal),
   93    safe_goal(Goal),
   94    call(Goal).
   95
   96%!  safe_goal(:Goal) is det.
   97%
   98%   True if calling Goal provides  no   security  risc. This implies
   99%   that:
  100%
  101%     - The call-graph can be fully expanded. Full expansion *stops*
  102%     if a meta-goal is found for   which we cannot determine enough
  103%     details to know which predicate will be called.
  104%
  105%     - All predicates  referenced  from   the  fully  expanded  are
  106%     whitelisted by the predicate safe_primitive/1 and safe_meta/2.
  107%
  108%     - It is not allowed to make explicitly qualified calls into
  109%     modules to predicates that are not exported or declared
  110%     public.
  111%
  112%   @error  instantiation_error if the analysis encounters a term in
  113%           a callable position that is insufficiently instantiated
  114%           to determine the predicate called.
  115%   @error  permission_error(call, sandboxed, Goal) if Goal is in
  116%           the call-tree and not white-listed.
  117
  118safe_goal(M:Goal) :-
  119    empty_assoc(Safe0),
  120    catch(safe(Goal, M, [], Safe0, _), E, true),
  121    !,
  122    nb_delete(sandbox_last_error),
  123    (   var(E)
  124    ->  true
  125    ;   throw(E)
  126    ).
  127safe_goal(_) :-
  128    nb_current(sandbox_last_error, E),
  129    !,
  130    nb_delete(sandbox_last_error),
  131    throw(E).
  132safe_goal(G) :-
  133    debug(sandbox(fail), 'safe_goal/1 failed for ~p', [G]),
  134    throw(error(instantiation_error, sandbox(G, []))).
  135
  136
  137%!  safe(+Goal, +Module, +Parents, +Safe0, -Safe) is semidet.
  138%
  139%   Is true if Goal can only call safe code.
  140
  141safe(V, _, Parents, _, _) :-
  142    var(V),
  143    !,
  144    Error = error(instantiation_error, sandbox(V, Parents)),
  145    nb_setval(sandbox_last_error, Error),
  146    throw(Error).
  147safe(M:G, _, Parents, Safe0, Safe) :-
  148    !,
  149    must_be(atom, M),
  150    must_be(callable, G),
  151    known_module(M:G, Parents),
  152    (   predicate_property(M:G, imported_from(M2))
  153    ->  true
  154    ;   M2 = M
  155    ),
  156    (   (   safe_primitive(M2:G)
  157        ;   safe_primitive(G),
  158            predicate_property(G, iso)
  159        )
  160    ->  Safe = Safe0
  161    ;   (   predicate_property(M:G, exported)
  162        ;   predicate_property(M:G, public)
  163        ;   predicate_property(M:G, multifile)
  164        ;   predicate_property(M:G, iso)
  165        ;   memberchk(M:_, Parents)
  166        )
  167    ->  safe(G, M, Parents, Safe0, Safe)
  168    ;   throw(error(permission_error(call, sandboxed, M:G),
  169                    sandbox(M:G, Parents)))
  170    ).
  171safe(G, _, Parents, _, _) :-
  172    debugging(sandbox(show)),
  173    length(Parents, Level),
  174    debug(sandbox(show), '[~D] SAFE ~q?', [Level, G]),
  175    fail.
  176safe(G, _, Parents, Safe, Safe) :-
  177    catch(safe_primitive(G),
  178          error(instantiation_error, _),
  179          rethrow_instantition_error([G|Parents])),
  180    predicate_property(G, iso),
  181    !.
  182safe(G, M, Parents, Safe, Safe) :-
  183    known_module(M:G, Parents),
  184    (   predicate_property(M:G, imported_from(M2))
  185    ->  true
  186    ;   M2 = M
  187    ),
  188    (   catch(safe_primitive(M2:G),
  189              error(instantiation_error, _),
  190              rethrow_instantition_error([M2:G|Parents]))
  191    ;   predicate_property(M2:G, number_of_rules(0))
  192    ),
  193    !.
  194safe(G, M, Parents, Safe0, Safe) :-
  195    predicate_property(G, iso),
  196    safe_meta_call(G, M, Called),
  197    !,
  198    add_iso_parent(G, Parents, Parents1),
  199    safe_list(Called, M, Parents1, Safe0, Safe).
  200safe(G, M, Parents, Safe0, Safe) :-
  201    (   predicate_property(M:G, imported_from(M2))
  202    ->  true
  203    ;   M2 = M
  204    ),
  205    safe_meta_call(M2:G, M, Called),
  206    !,
  207    safe_list(Called, M, Parents, Safe0, Safe).
  208safe(G, M, Parents, Safe0, Safe) :-
  209    goal_id(M:G, Id, Gen),
  210    (   get_assoc(Id, Safe0, _)
  211    ->  Safe = Safe0
  212    ;   put_assoc(Id, Safe0, true, Safe1),
  213        (   Gen == M:G
  214        ->  safe_clauses(Gen, M, [Id|Parents], Safe1, Safe)
  215        ;   catch(safe_clauses(Gen, M, [Id|Parents], Safe1, Safe),
  216                  error(instantiation_error, Ctx),
  217                  unsafe(Parents, Ctx))
  218        )
  219    ),
  220    !.
  221safe(G, M, Parents, _, _) :-
  222    debug(sandbox(fail),
  223          'safe/1 failed for ~p (parents:~p)', [M:G, Parents]),
  224    fail.
  225
  226unsafe(Parents, Var) :-
  227    var(Var),
  228    !,
  229    nb_setval(sandbox_last_error,
  230              error(instantiation_error, sandbox(_, Parents))),
  231    fail.
  232unsafe(_Parents, Ctx) :-
  233    Ctx = sandbox(_,_),
  234    nb_setval(sandbox_last_error,
  235              error(instantiation_error, Ctx)),
  236    fail.
  237
  238rethrow_instantition_error(Parents) :-
  239    throw(error(instantiation_error, sandbox(_, Parents))).
  240
  241safe_clauses(G, M, Parents, Safe0, Safe) :-
  242    predicate_property(M:G, interpreted),
  243    def_module(M:G, MD:QG),
  244    \+ compiled(MD:QG),
  245    !,
  246    findall(Ref-Body, clause(MD:QG, Body, Ref), Bodies),
  247    safe_bodies(Bodies, MD, Parents, Safe0, Safe).
  248safe_clauses(G, M, [_|Parents], _, _) :-
  249    predicate_property(M:G, visible),
  250    !,
  251    throw(error(permission_error(call, sandboxed, G),
  252                sandbox(M:G, Parents))).
  253safe_clauses(_, _, [G|Parents], _, _) :-
  254    throw(error(existence_error(procedure, G),
  255                sandbox(G, Parents))).
  256
  257compiled(system:(@(_,_))).
  258
  259known_module(M:_, _) :-
  260    current_module(M),
  261    !.
  262known_module(M:G, Parents) :-
  263    throw(error(permission_error(call, sandboxed, M:G),
  264                sandbox(M:G, Parents))).
  265
  266add_iso_parent(G, Parents, Parents) :-
  267    is_control(G),
  268    !.
  269add_iso_parent(G, Parents, [G|Parents]).
  270
  271is_control((_,_)).
  272is_control((_;_)).
  273is_control((_->_)).
  274is_control((_*->_)).
  275is_control(\+(_)).
  276
  277
  278%!  safe_bodies(+Bodies, +Module, +Parents, +Safe0, -Safe)
  279%
  280%   Verify the safety of bodies. If  a   clause  was compiled with a
  281%   qualified module, we  consider  execution  of   the  body  in  a
  282%   different module _not_ a cross-module call.
  283
  284safe_bodies([], _, _, Safe, Safe).
  285safe_bodies([Ref-H|T], M, Parents, Safe0, Safe) :-
  286    (   H = M2:H2, nonvar(M2),
  287        clause_property(Ref, module(M2))
  288    ->  copy_term(H2, H3),
  289        CM = M2
  290    ;   copy_term(H, H3),
  291        CM = M
  292    ),
  293    safe(H3, CM, Parents, Safe0, Safe1),
  294    safe_bodies(T, M, Parents, Safe1, Safe).
  295
  296def_module(M:G, MD:QG) :-
  297    predicate_property(M:G, imported_from(MD)),
  298    !,
  299    meta_qualify(MD:G, M, QG).
  300def_module(M:G, M:QG) :-
  301    meta_qualify(M:G, M, QG).
  302
  303%!  safe_list(+Called, +Module, +Parents, +Safe0, -Safe)
  304%
  305%   Processed objects called through meta  predicates. If the called
  306%   object  is  in  our  current  context    we  remove  the  module
  307%   qualification to avoid the cross-module check.
  308
  309safe_list([], _, _, Safe, Safe).
  310safe_list([H|T], M, Parents, Safe0, Safe) :-
  311    (   H = M2:H2,
  312        M == M2                             % in our context
  313    ->  copy_term(H2, H3)
  314    ;   copy_term(H, H3)                    % cross-module call
  315    ),
  316    safe(H3, M, Parents, Safe0, Safe1),
  317    safe_list(T, M, Parents, Safe1, Safe).
  318
  319%!  meta_qualify(:G, +M, -QG) is det.
  320%
  321%   Perform meta-qualification of the goal-argument
  322
  323meta_qualify(MD:G, M, QG) :-
  324    predicate_property(MD:G, meta_predicate(Head)),
  325    !,
  326    G =.. [Name|Args],
  327    Head =.. [_|Q],
  328    qualify_args(Q, M, Args, QArgs),
  329    QG =.. [Name|QArgs].
  330meta_qualify(_:G, _, G).
  331
  332qualify_args([], _, [], []).
  333qualify_args([H|T], M, [A|AT], [Q|QT]) :-
  334    qualify_arg(H, M, A, Q),
  335    qualify_args(T, M, AT, QT).
  336
  337qualify_arg(S, M, A, Q) :-
  338    q_arg(S),
  339    !,
  340    qualify(A, M, Q).
  341qualify_arg(_, _, A, A).
  342
  343q_arg(I) :- integer(I), !.
  344q_arg(:).
  345q_arg(^).
  346q_arg(//).
  347
  348qualify(A, M, MZ:Q) :-
  349    strip_module(M:A, MZ, Q).
  350
  351%!  goal_id(:Goal, -Id, -Gen) is nondet.
  352%
  353%   Generate an identifier for the goal proven to be safe. We
  354%   first try to prove the most general form of the goal.  If
  355%   this fails, we try to prove more specific versions.
  356%
  357%   @tbd    Do step-by-step generalisation instead of the current
  358%           two levels (most general and most specific).
  359%   @tbd    We could also use variant_sha1 for the goal ids.
  360
  361goal_id(M:Goal, M:Id, Gen) :-
  362    !,
  363    goal_id(Goal, Id, Gen).
  364goal_id(Var, _, _) :-
  365    var(Var),
  366    !,
  367    instantiation_error(Var).
  368goal_id(Atom, Atom, Atom) :-
  369    atom(Atom),
  370    !.
  371goal_id(Term, _, _) :-
  372    \+ compound(Term),
  373    !,
  374    type_error(callable, Term).
  375goal_id(Term, Skolem, Gen) :-           % most general form
  376    compound_name_arity(Term, Name, Arity),
  377    compound_name_arity(Skolem, Name, Arity),
  378    compound_name_arity(Gen, Name, Arity),
  379    copy_goal_args(1, Term, Skolem, Gen),
  380    (   Gen =@= Term
  381    ->  !                           % No more specific one; we can commit
  382    ;   true
  383    ),
  384    numbervars(Skolem, 0, _).
  385goal_id(Term, Skolem, Term) :-          % most specific form
  386    debug(sandbox(specify), 'Retrying with ~p', [Term]),
  387    copy_term(Term, Skolem),
  388    numbervars(Skolem, 0, _).
  389
  390%!  copy_goal_args(+I, +Term, +Skolem, +Gen) is det.
  391%
  392%   Create  the  most  general  form,   but  keep  module  qualified
  393%   arguments because they will likely be called anyway.
  394
  395copy_goal_args(I, Term, Skolem, Gen) :-
  396    arg(I, Term, TA),
  397    !,
  398    arg(I, Skolem, SA),
  399    arg(I, Gen, GA),
  400    copy_goal_arg(TA, SA, GA),
  401    I2 is I + 1,
  402    copy_goal_args(I2, Term, Skolem, Gen).
  403copy_goal_args(_, _, _, _).
  404
  405copy_goal_arg(Arg, SArg, Arg) :-
  406    copy_goal_arg(Arg),
  407    !,
  408    copy_term(Arg, SArg).
  409copy_goal_arg(_, _, _).
  410
  411copy_goal_arg(Var) :- var(Var), !, fail.
  412copy_goal_arg(_:_).
  413
  414%!  verify_safe_declaration(+Decl)
  415%
  416%   See whether a  safe  declaration  makes   sense.  That  is,  the
  417%   predicate must be defined (such that  the attacker cannot define
  418%   the predicate), must be sufficiently   instantiated and only ISO
  419%   declared predicates may omit a module qualification.
  420%
  421%   @tbd    Verify safe_meta/2 declarations.  It is a bit less clear
  422%           what the rules are.
  423
  424term_expansion(safe_primitive(Goal), Term) :-
  425    (   verify_safe_declaration(Goal)
  426    ->  Term = safe_primitive(Goal)
  427    ;   Term = []
  428    ).
  429
  430system:term_expansion(sandbox:safe_primitive(Goal), Term) :-
  431    \+ current_prolog_flag(xref, true),
  432    (   verify_safe_declaration(Goal)
  433    ->  Term = sandbox:safe_primitive(Goal)
  434    ;   Term = []
  435    ).
  436
  437verify_safe_declaration(Var) :-
  438    var(Var),
  439    !,
  440    instantiation_error(Var).
  441verify_safe_declaration(Module:Goal) :-
  442    !,
  443    must_be(atom, Module),
  444    must_be(callable, Goal),
  445    (   ok_meta(Module:Goal)
  446    ->  true
  447    ;   (   predicate_property(Module:Goal, visible)
  448        ->  true
  449        ;   predicate_property(Module:Goal, foreign)
  450        ),
  451        \+ predicate_property(Module:Goal, imported_from(_)),
  452        \+ predicate_property(Module:Goal, meta_predicate(_))
  453    ->  true
  454    ;   permission_error(declare, safe_goal, Module:Goal)
  455    ).
  456verify_safe_declaration(Goal) :-
  457    must_be(callable, Goal),
  458    (   predicate_property(system:Goal, iso),
  459        \+ predicate_property(system:Goal, meta_predicate())
  460    ->  true
  461    ;   permission_error(declare, safe_goal, Goal)
  462    ).
  463
  464ok_meta(system:assert(_)).
  465ok_meta(system:use_module(_,_)).
  466ok_meta(system:use_module(_)).
  467
  468verify_predefined_safe_declarations :-
  469    forall(clause(safe_primitive(Goal), _Body, Ref),
  470           ( catch(verify_safe_declaration(Goal), E, true),
  471             (   nonvar(E)
  472             ->  clause_property(Ref, file(File)),
  473                 clause_property(Ref, line_count(Line)),
  474                 print_message(error, bad_safe_declaration(Goal, File, Line))
  475             ;   true
  476             )
  477           )).
  478
  479:- initialization(verify_predefined_safe_declarations, now).  480
  481%!  safe_primitive(?Goal) is nondet.
  482%
  483%   True if Goal is safe  to   call  (i.e.,  cannot access dangerous
  484%   system-resources and cannot upset  other   parts  of  the Prolog
  485%   process). There are two  types  of   facts.  ISO  built-ins  are
  486%   declared without a module prefix. This is safe because it is not
  487%   allowed to (re-)define these  primitives   (i.e.,  give  them an
  488%   unsafe     implementation)     and     the       way      around
  489%   (redefine_system_predicate/1) is unsafe.  The   other  group are
  490%   module-qualified and only match if the   system  infers that the
  491%   predicate is imported from the given module.
  492
  493% First, all ISO system predicates that are considered safe
  494
  495safe_primitive(true).
  496safe_primitive(fail).
  497safe_primitive(system:false).
  498safe_primitive(repeat).
  499safe_primitive(!).
  500                                        % types
  501safe_primitive(var(_)).
  502safe_primitive(nonvar(_)).
  503safe_primitive(system:attvar(_)).
  504safe_primitive(integer(_)).
  505safe_primitive(float(_)).
  506safe_primitive(system:rational(_)).
  507safe_primitive(number(_)).
  508safe_primitive(atom(_)).
  509safe_primitive(system:blob(_,_)).
  510safe_primitive(system:string(_)).
  511safe_primitive(atomic(_)).
  512safe_primitive(compound(_)).
  513safe_primitive(callable(_)).
  514safe_primitive(ground(_)).
  515safe_primitive(system:cyclic_term(_)).
  516safe_primitive(acyclic_term(_)).
  517safe_primitive(system:is_stream(_)).
  518safe_primitive(system:'$is_char'(_)).
  519safe_primitive(system:'$is_char_code'(_)).
  520safe_primitive(system:'$is_char_list'(_,_)).
  521safe_primitive(system:'$is_code_list'(_,_)).
  522                                        % ordering
  523safe_primitive(@>(_,_)).
  524safe_primitive(@>=(_,_)).
  525safe_primitive(==(_,_)).
  526safe_primitive(@<(_,_)).
  527safe_primitive(@=<(_,_)).
  528safe_primitive(compare(_,_,_)).
  529safe_primitive(sort(_,_)).
  530safe_primitive(keysort(_,_)).
  531safe_primitive(system: =@=(_,_)).
  532safe_primitive(system:'$btree_find_node'(_,_,_,_,_)).
  533
  534                                        % unification and equivalence
  535safe_primitive(=(_,_)).
  536safe_primitive(\=(_,_)).
  537safe_primitive(system:'?='(_,_)).
  538safe_primitive(system:unifiable(_,_,_)).
  539safe_primitive(unify_with_occurs_check(_,_)).
  540safe_primitive(\==(_,_)).
  541                                        % arithmetic
  542safe_primitive(is(_,_)).
  543safe_primitive(>(_,_)).
  544safe_primitive(>=(_,_)).
  545safe_primitive(=:=(_,_)).
  546safe_primitive(=\=(_,_)).
  547safe_primitive(=<(_,_)).
  548safe_primitive(<(_,_)).
  549:- if(current_prolog_flag(bounded, false)).  550safe_primitive(system:nth_integer_root_and_remainder(_,_,_,_)).
  551:- endif.  552
  553                                        % term-handling
  554safe_primitive(arg(_,_,_)).
  555safe_primitive(system:setarg(_,_,_)).
  556safe_primitive(system:nb_setarg(_,_,_)).
  557safe_primitive(system:nb_linkarg(_,_,_)).
  558safe_primitive(functor(_,_,_)).
  559safe_primitive(_ =.. _).
  560safe_primitive(system:compound_name_arity(_,_,_)).
  561safe_primitive(system:compound_name_arguments(_,_,_)).
  562safe_primitive(system:'$filled_array'(_,_,_,_)).
  563safe_primitive(copy_term(_,_)).
  564safe_primitive(system:duplicate_term(_,_)).
  565safe_primitive(system:copy_term_nat(_,_)).
  566safe_primitive(system:size_abstract_term(_,_,_)).
  567safe_primitive(numbervars(_,_,_)).
  568safe_primitive(system:numbervars(_,_,_,_)).
  569safe_primitive(subsumes_term(_,_)).
  570safe_primitive(system:term_hash(_,_)).
  571safe_primitive(system:term_hash(_,_,_,_)).
  572safe_primitive(system:variant_sha1(_,_)).
  573safe_primitive(system:variant_hash(_,_)).
  574safe_primitive(system:'$term_size'(_,_,_)).
  575
  576                                        % dicts
  577safe_primitive(system:is_dict(_)).
  578safe_primitive(system:is_dict(_,_)).
  579safe_primitive(system:get_dict(_,_,_)).
  580safe_primitive(system:get_dict(_,_,_,_,_)).
  581safe_primitive(system:'$get_dict_ex'(_,_,_)).
  582safe_primitive(system:dict_create(_,_,_)).
  583safe_primitive(system:dict_pairs(_,_,_)).
  584safe_primitive(system:put_dict(_,_,_)).
  585safe_primitive(system:put_dict(_,_,_,_)).
  586safe_primitive(system:del_dict(_,_,_,_)).
  587safe_primitive(system:select_dict(_,_,_)).
  588safe_primitive(system:b_set_dict(_,_,_)).
  589safe_primitive(system:nb_set_dict(_,_,_)).
  590safe_primitive(system:nb_link_dict(_,_,_)).
  591safe_primitive(system:(:<(_,_))).
  592safe_primitive(system:(>:<(_,_))).
  593                                        % atoms
  594safe_primitive(atom_chars(_, _)).
  595safe_primitive(atom_codes(_, _)).
  596safe_primitive(sub_atom(_,_,_,_,_)).
  597safe_primitive(atom_concat(_,_,_)).
  598safe_primitive(atom_length(_,_)).
  599safe_primitive(char_code(_,_)).
  600safe_primitive(system:name(_,_)).
  601safe_primitive(system:atomic_concat(_,_,_)).
  602safe_primitive(system:atomic_list_concat(_,_)).
  603safe_primitive(system:atomic_list_concat(_,_,_)).
  604safe_primitive(system:downcase_atom(_,_)).
  605safe_primitive(system:upcase_atom(_,_)).
  606safe_primitive(system:char_type(_,_)).
  607safe_primitive(system:normalize_space(_,_)).
  608safe_primitive(system:sub_atom_icasechk(_,_,_)).
  609                                        % numbers
  610safe_primitive(number_codes(_,_)).
  611safe_primitive(number_chars(_,_)).
  612safe_primitive(system:atom_number(_,_)).
  613safe_primitive(system:code_type(_,_)).
  614                                        % strings
  615safe_primitive(system:atom_string(_,_)).
  616safe_primitive(system:number_string(_,_)).
  617safe_primitive(system:string_chars(_, _)).
  618safe_primitive(system:string_codes(_, _)).
  619safe_primitive(system:string_code(_,_,_)).
  620safe_primitive(system:sub_string(_,_,_,_,_)).
  621safe_primitive(system:split_string(_,_,_,_)).
  622safe_primitive(system:atomics_to_string(_,_,_)).
  623safe_primitive(system:atomics_to_string(_,_)).
  624safe_primitive(system:string_concat(_,_,_)).
  625safe_primitive(system:string_length(_,_)).
  626safe_primitive(system:string_lower(_,_)).
  627safe_primitive(system:string_upper(_,_)).
  628safe_primitive(system:term_string(_,_)).
  629safe_primitive('$syspreds':term_string(_,_,_)).
  630                                        % Lists
  631safe_primitive(length(_,_)).
  632                                        % exceptions
  633safe_primitive(throw(_)).
  634safe_primitive(system:abort).
  635                                        % misc
  636safe_primitive(current_prolog_flag(_,_)).
  637safe_primitive(current_op(_,_,_)).
  638safe_primitive(system:sleep(_)).
  639safe_primitive(system:thread_self(_)).
  640safe_primitive(system:get_time(_)).
  641safe_primitive(system:statistics(_,_)).
  642safe_primitive(system:thread_statistics(Id,_,_)) :-
  643    (   var(Id)
  644    ->  instantiation_error(Id)
  645    ;   thread_self(Id)
  646    ).
  647safe_primitive(system:thread_property(Id,_)) :-
  648    (   var(Id)
  649    ->  instantiation_error(Id)
  650    ;   thread_self(Id)
  651    ).
  652safe_primitive(system:format_time(_,_,_)).
  653safe_primitive(system:format_time(_,_,_,_)).
  654safe_primitive(system:date_time_stamp(_,_)).
  655safe_primitive(system:stamp_date_time(_,_,_)).
  656safe_primitive(system:strip_module(_,_,_)).
  657safe_primitive('$messages':message_to_string(_,_)).
  658safe_primitive(system:import_module(_,_)).
  659safe_primitive(system:file_base_name(_,_)).
  660safe_primitive(system:file_directory_name(_,_)).
  661safe_primitive(system:file_name_extension(_,_,_)).
  662
  663safe_primitive(clause(H,_)) :- safe_clause(H).
  664safe_primitive(asserta(X)) :- safe_assert(X).
  665safe_primitive(assertz(X)) :- safe_assert(X).
  666safe_primitive(retract(X)) :- safe_assert(X).
  667safe_primitive(retractall(X)) :- safe_assert(X).
  668
  669% We need to do data flow analysis to find the tag of the
  670% target key before we can conclude that functions on dicts
  671% are safe.
  672safe_primitive('$dicts':'.'(_,K,_)) :- atom(K).
  673safe_primitive('$dicts':'.'(_,K,_)) :-
  674    (   nonvar(K)
  675    ->  dict_built_in(K)
  676    ;   instantiation_error(K)
  677    ).
  678
  679dict_built_in(get(_)).
  680dict_built_in(put(_)).
  681dict_built_in(put(_,_)).
  682
  683% The non-ISO system predicates.  These can be redefined, so we must
  684% be careful to ensure the system ones are used.
  685
  686safe_primitive(system:false).
  687safe_primitive(system:cyclic_term(_)).
  688safe_primitive(system:msort(_,_)).
  689safe_primitive(system:sort(_,_,_,_)).
  690safe_primitive(system:between(_,_,_)).
  691safe_primitive(system:succ(_,_)).
  692safe_primitive(system:plus(_,_,_)).
  693safe_primitive(system:float_class(_,_)).
  694safe_primitive(system:term_variables(_,_)).
  695safe_primitive(system:term_variables(_,_,_)).
  696safe_primitive(system:'$term_size'(_,_,_)).
  697safe_primitive(system:atom_to_term(_,_,_)).
  698safe_primitive(system:term_to_atom(_,_)).
  699safe_primitive(system:atomic_list_concat(_,_,_)).
  700safe_primitive(system:atomic_list_concat(_,_)).
  701safe_primitive(system:downcase_atom(_,_)).
  702safe_primitive(system:upcase_atom(_,_)).
  703safe_primitive(system:is_list(_)).
  704safe_primitive(system:memberchk(_,_)).
  705safe_primitive(system:'$skip_list'(_,_,_)).
  706                                        % attributes
  707safe_primitive(system:get_attr(_,_,_)).
  708safe_primitive(system:get_attrs(_,_)).
  709safe_primitive(system:term_attvars(_,_)).
  710safe_primitive(system:del_attr(_,_)).
  711safe_primitive(system:del_attrs(_)).
  712safe_primitive('$attvar':copy_term(_,_,_)).
  713                                        % globals
  714safe_primitive(system:b_getval(_,_)).
  715safe_primitive(system:b_setval(Var,_)) :-
  716    safe_global_var(Var).
  717safe_primitive(system:nb_getval(_,_)).
  718safe_primitive('$syspreds':nb_setval(Var,_)) :-
  719    safe_global_var(Var).
  720safe_primitive(system:nb_linkval(Var,_)) :-
  721    safe_global_var(Var).
  722safe_primitive(system:nb_current(_,_)).
  723                                        % database
  724safe_primitive(system:assert(X)) :-
  725    safe_assert(X).
  726                                        % Output
  727safe_primitive(system:writeln(_)).
  728safe_primitive('$messages':print_message(_,_)).
  729
  730                                        % Stack limits (down)
  731safe_primitive('$syspreds':set_prolog_stack(Stack, limit(ByteExpr))) :-
  732    nonvar(Stack),
  733    stack_name(Stack),
  734    catch(Bytes is ByteExpr, _, fail),
  735    prolog_stack_property(Stack, limit(Current)),
  736    Bytes =< Current.
  737
  738stack_name(global).
  739stack_name(local).
  740stack_name(trail).
  741
  742safe_primitive('$tabling':abolish_all_tables).
  743safe_primitive('$tabling':'$wrap_tabled'(Module:_Head, _Mode)) :-
  744    prolog_load_context(module, Module),
  745    !.
  746safe_primitive('$tabling':'$moded_wrap_tabled'(Module:_Head,_,_,_)) :-
  747    prolog_load_context(module, Module),
  748    !.
  749
  750
  751% use_module/1.  We only allow for .pl files that are loaded from
  752% relative paths that do not contain /../
  753
  754safe_primitive(system:use_module(Spec, _Import)) :-
  755    safe_primitive(system:use_module(Spec)).
  756safe_primitive(system:use_module(Spec)) :-
  757    ground(Spec),
  758    (   atom(Spec)
  759    ->  Path = Spec
  760    ;   Spec =.. [_Alias, Segments],
  761        phrase(segments_to_path(Segments), List),
  762        atomic_list_concat(List, Path)
  763    ),
  764    \+ is_absolute_file_name(Path),
  765    \+ sub_atom(Path, _, _, _, '/../'),
  766    absolute_file_name(Spec, AbsFile,
  767                       [ access(read),
  768                         file_type(prolog),
  769                         file_errors(fail)
  770                       ]),
  771    file_name_extension(_, Ext, AbsFile),
  772    save_extension(Ext).
  773
  774% support predicates for safe_primitive, validating the safety of
  775% arguments to certain goals.
  776
  777segments_to_path(A/B) -->
  778    !,
  779    segments_to_path(A),
  780    [/],
  781    segments_to_path(B).
  782segments_to_path(X) -->
  783    [X].
  784
  785save_extension(pl).
  786
  787%!  safe_assert(+Term) is semidet.
  788%
  789%   True if assert(Term) is safe,  which   means  it  asserts in the
  790%   current module. Cross-module asserts are   considered unsafe. We
  791%   only allow for adding facts. In theory,  we could also allow for
  792%   rules if we prove the safety of the body.
  793
  794safe_assert(C) :- cyclic_term(C), !, fail.
  795safe_assert(X) :- var(X), !, fail.
  796safe_assert(_Head:-_Body) :- !, fail.
  797safe_assert(_:_) :- !, fail.
  798safe_assert(_).
  799
  800%!  safe_clause(+Head) is semidet.
  801%
  802%   Consider a call to clause safe if  it   does  not try to cross a
  803%   module boundary. Cross-module usage  of   clause/2  can  extract
  804%   private information from other modules.
  805
  806safe_clause(H) :- var(H), !.
  807safe_clause(_:_) :- !, fail.
  808safe_clause(_).
  809
  810
  811%!  safe_global_var(+Name) is semidet.
  812%
  813%   True if Name  is  a  global   variable  to  which  assertion  is
  814%   considered safe.
  815
  816safe_global_var(Name) :-
  817    var(Name),
  818    !,
  819    instantiation_error(Name).
  820safe_global_var(Name) :-
  821    safe_global_variable(Name).
  822
  823%!  safe_global_variable(Name) is semidet.
  824%
  825%   Declare the given global variable safe to write to.
  826
  827
  828%!  safe_meta(+Goal, -Called:list(callable)) is semidet.
  829%
  830%   Hook. True if Goal is a   meta-predicate that is considered safe
  831%   iff all elements in Called are safe.
  832
  833safe_meta(system:put_attr(V,M,A), Called) :-
  834    !,
  835    (   atom(M)
  836    ->  attr_hook_predicates([ attr_unify_hook(A, _),
  837                               attribute_goals(V,_,_),
  838                               project_attributes(_,_)
  839                             ], M, Called)
  840    ;   instantiation_error(M)
  841    ).
  842safe_meta(system:with_output_to(Output, G), [G]) :-
  843    safe_output(Output),
  844    !.
  845safe_meta(system:format(Format, Args), Calls) :-
  846    format_calls(Format, Args, Calls).
  847safe_meta(system:format(Output, Format, Args), Calls) :-
  848    safe_output(Output),
  849    format_calls(Format, Args, Calls).
  850safe_meta(prolog_debug:debug(_Term, Format, Args), Calls) :-
  851    format_calls(Format, Args, Calls).
  852safe_meta(system:set_prolog_flag(Flag, Value), []) :-
  853    atom(Flag),
  854    safe_prolog_flag(Flag, Value).
  855safe_meta('$attvar':freeze(_Var,Goal), [Goal]).
  856safe_meta(phrase(NT,Xs0,Xs), [Goal]) :- % phrase/2,3 and call_dcg/2,3
  857    expand_nt(NT,Xs0,Xs,Goal).
  858safe_meta(phrase(NT,Xs0), [Goal]) :-
  859    expand_nt(NT,Xs0,[],Goal).
  860safe_meta('$dcg':call_dcg(NT,Xs0,Xs), [Goal]) :-
  861    expand_nt(NT,Xs0,Xs,Goal).
  862safe_meta('$dcg':call_dcg(NT,Xs0), [Goal]) :-
  863    expand_nt(NT,Xs0,[],Goal).
  864safe_meta('$tabling':abolish_table_subgoals(V), []) :-
  865    \+ qualified(V).
  866safe_meta('$tabling':current_table(V, _), []) :-
  867    \+ qualified(V).
  868safe_meta('$tabling':tnot(G), [G]).
  869safe_meta('$tabling':not_exists(G), [G]).
  870
  871qualified(V) :-
  872    nonvar(V),
  873    V = _:_.
  874
  875%!  attr_hook_predicates(+Hooks0, +Module, -Hooks) is det.
  876%
  877%   Filter the defined hook implementations.   This  is safe because
  878%   (1) calling an undefined predicate is   not  a safety issue, (2)
  879%   the  user  an  only  assert  in  the  current  module  and  only
  880%   predicates that have a safe body. This avoids the need to define
  881%   attribute hooks solely for the purpose of making them safe.
  882
  883attr_hook_predicates([], _, []).
  884attr_hook_predicates([H|T], M, Called) :-
  885    (   predicate_property(M:H, defined)
  886    ->  Called = [M:H|Rest]
  887    ;   Called = Rest
  888    ),
  889    attr_hook_predicates(T, M, Rest).
  890
  891
  892%!  expand_nt(+NT, ?Xs0, ?Xs, -NewGoal)
  893%
  894%   Similar to expand_phrase/2, but we do   throw  errors instead of
  895%   failing if NT is not sufficiently instantiated.
  896
  897expand_nt(NT, _Xs0, _Xs, _NewGoal) :-
  898    strip_module(NT, _, Plain),
  899    var(Plain),
  900    !,
  901    instantiation_error(Plain).
  902expand_nt(NT, Xs0, Xs, NewGoal) :-
  903    dcg_translate_rule((pseudo_nt --> NT),
  904                       (pseudo_nt(Xs0c,Xsc) :- NewGoal0)),
  905    (   var(Xsc), Xsc \== Xs0c
  906    ->  Xs = Xsc, NewGoal1 = NewGoal0
  907    ;   NewGoal1 = (NewGoal0, Xsc = Xs)
  908    ),
  909    (   var(Xs0c)
  910    ->  Xs0 = Xs0c,
  911        NewGoal = NewGoal1
  912    ;   NewGoal = ( Xs0 = Xs0c, NewGoal1 )
  913    ).
  914
  915%!  safe_meta_call(+Goal, +Context, -Called:list(callable)) is semidet.
  916%
  917%   True if Goal is a   meta-predicate that is considered safe
  918%   iff all elements in Called are safe.
  919
  920safe_meta_call(Goal, _, _Called) :-
  921    debug(sandbox(meta), 'Safe meta ~p?', [Goal]),
  922    fail.
  923safe_meta_call(Goal, Context, Called) :-
  924    (   safe_meta(Goal, Called)
  925    ->  true
  926    ;   safe_meta(Goal, Context, Called)
  927    ),
  928    !.     % call hook
  929safe_meta_call(Goal, _, Called) :-
  930    Goal = M:Plain,
  931    compound(Plain),
  932    compound_name_arity(Plain, Name, Arity),
  933    safe_meta_predicate(M:Name/Arity),
  934    predicate_property(Goal, meta_predicate(Spec)),
  935    !,
  936    called(Spec, Plain, Called).
  937safe_meta_call(M:Goal, _, Called) :-
  938    !,
  939    generic_goal(Goal, Gen),
  940    safe_meta(M:Gen),
  941    called(Gen, Goal, Called).
  942safe_meta_call(Goal, _, Called) :-
  943    generic_goal(Goal, Gen),
  944    safe_meta(Gen),
  945    called(Gen, Goal, Called).
  946
  947called(Gen, Goal, Called) :-
  948    compound_name_arity(Goal, _, Arity),
  949    called(1, Arity, Gen, Goal, Called).
  950
  951called(I, Arity, Gen, Goal, Called) :-
  952    I =< Arity,
  953    !,
  954    arg(I, Gen, Spec),
  955    (   calling_meta_spec(Spec)
  956    ->  arg(I, Goal, Called0),
  957        extend(Spec, Called0, G),
  958        Called = [G|Rest]
  959    ;   Called = Rest
  960    ),
  961    I2 is I+1,
  962    called(I2, Arity, Gen, Goal, Rest).
  963called(_, _, _, _, []).
  964
  965generic_goal(G, Gen) :-
  966    functor(G, Name, Arity),
  967    functor(Gen, Name, Arity).
  968
  969calling_meta_spec(V) :- var(V), !, fail.
  970calling_meta_spec(I) :- integer(I), !.
  971calling_meta_spec(^).
  972calling_meta_spec(//).
  973
  974
  975extend(^, G, Plain) :-
  976    !,
  977    strip_existential(G, Plain).
  978extend(//, DCG, Goal) :-
  979    !,
  980    (   expand_phrase(call_dcg(DCG,_,_), Goal)
  981    ->  true
  982    ;   instantiation_error(DCG)    % Ask more instantiation.
  983    ).                              % might not help, but does not harm.
  984extend(0, G, G) :- !.
  985extend(I, M:G0, M:G) :-
  986    !,
  987    G0 =.. List,
  988    length(Extra, I),
  989    append(List, Extra, All),
  990    G =.. All.
  991extend(I, G0, G) :-
  992    G0 =.. List,
  993    length(Extra, I),
  994    append(List, Extra, All),
  995    G =.. All.
  996
  997strip_existential(Var, Var) :-
  998    var(Var),
  999    !.
 1000strip_existential(M:G0, M:G) :-
 1001    !,
 1002    strip_existential(G0, G).
 1003strip_existential(_^G0, G) :-
 1004    !,
 1005    strip_existential(G0, G).
 1006strip_existential(G, G).
 1007
 1008%!  safe_meta(?Template).
 1009
 1010safe_meta((0,0)).
 1011safe_meta((0;0)).
 1012safe_meta((0->0)).
 1013safe_meta(system:(0*->0)).
 1014safe_meta(catch(0,*,0)).
 1015safe_meta(findall(*,0,*)).
 1016safe_meta('$bags':findall(*,0,*,*)).
 1017safe_meta(setof(*,^,*)).
 1018safe_meta(bagof(*,^,*)).
 1019safe_meta('$bags':findnsols(*,*,0,*)).
 1020safe_meta('$bags':findnsols(*,*,0,*,*)).
 1021safe_meta(system:call_cleanup(0,0)).
 1022safe_meta(system:setup_call_cleanup(0,0,0)).
 1023safe_meta(system:setup_call_catcher_cleanup(0,0,*,0)).
 1024safe_meta('$attvar':call_residue_vars(0,*)).
 1025safe_meta('$syspreds':call_with_inference_limit(0,*,*)).
 1026safe_meta('$syspreds':call_with_depth_limit(0,*,*)).
 1027safe_meta(^(*,0)).
 1028safe_meta(\+(0)).
 1029safe_meta(call(0)).
 1030safe_meta(call(1,*)).
 1031safe_meta(call(2,*,*)).
 1032safe_meta(call(3,*,*,*)).
 1033safe_meta(call(4,*,*,*,*)).
 1034safe_meta(call(5,*,*,*,*,*)).
 1035safe_meta(call(6,*,*,*,*,*,*)).
 1036safe_meta('$tabling':start_tabling(*,0)).
 1037safe_meta('$tabling':start_tabling(*,0,*,*)).
 1038
 1039%!  safe_output(+Output)
 1040%
 1041%   True if something is a safe output argument for with_output_to/2
 1042%   and friends. We do not want writing to streams.
 1043
 1044safe_output(Output) :-
 1045    var(Output),
 1046    !,
 1047    instantiation_error(Output).
 1048safe_output(atom(_)).
 1049safe_output(string(_)).
 1050safe_output(codes(_)).
 1051safe_output(codes(_,_)).
 1052safe_output(chars(_)).
 1053safe_output(chars(_,_)).
 1054safe_output(current_output).
 1055safe_output(current_error).
 1056
 1057%!  format_calls(+Format, +FormatArgs, -Calls)
 1058%
 1059%   Find ~@ calls from Format and Args.
 1060
 1061:- public format_calls/3.                       % used in pengines_io
 1062
 1063format_calls(Format, _Args, _Calls) :-
 1064    var(Format),
 1065    !,
 1066    instantiation_error(Format).
 1067format_calls(Format, Args, Calls) :-
 1068    format_types(Format, Types),
 1069    (   format_callables(Types, Args, Calls)
 1070    ->  true
 1071    ;   throw(error(format_error(Format, Types, Args), _))
 1072    ).
 1073
 1074format_callables([], [], []).
 1075format_callables([callable|TT], [G|TA], [G|TG]) :-
 1076    !,
 1077    format_callables(TT, TA, TG).
 1078format_callables([_|TT], [_|TA], TG) :-
 1079    !,
 1080    format_callables(TT, TA, TG).
 1081
 1082
 1083                 /*******************************
 1084                 *    SAFE COMPILATION HOOKS    *
 1085                 *******************************/
 1086
 1087:- multifile
 1088    prolog:sandbox_allowed_directive/1,
 1089    prolog:sandbox_allowed_goal/1,
 1090    prolog:sandbox_allowed_expansion/1. 1091
 1092%!  prolog:sandbox_allowed_directive(:G) is det.
 1093%
 1094%   Throws an exception if G is not considered a safe directive.
 1095
 1096prolog:sandbox_allowed_directive(Directive) :-
 1097    debug(sandbox(directive), 'Directive: ~p', [Directive]),
 1098    fail.
 1099prolog:sandbox_allowed_directive(Directive) :-
 1100    safe_directive(Directive),
 1101    !.
 1102prolog:sandbox_allowed_directive(M:PredAttr) :-
 1103    \+ prolog_load_context(module, M),
 1104    !,
 1105    debug(sandbox(directive), 'Cross-module directive', []),
 1106    permission_error(execute, sandboxed_directive, (:- M:PredAttr)).
 1107prolog:sandbox_allowed_directive(M:PredAttr) :-
 1108    safe_pattr(PredAttr),
 1109    !,
 1110    PredAttr =.. [Attr, Preds],
 1111    (   safe_pattr(Preds, Attr)
 1112    ->  true
 1113    ;   permission_error(execute, sandboxed_directive, (:- M:PredAttr))
 1114    ).
 1115prolog:sandbox_allowed_directive(_:Directive) :-
 1116    safe_source_directive(Directive),
 1117    !.
 1118prolog:sandbox_allowed_directive(_:Directive) :-
 1119    directive_loads_file(Directive, File),
 1120    !,
 1121    safe_path(File).
 1122prolog:sandbox_allowed_directive(G) :-
 1123    safe_goal(G).
 1124
 1125%!  safe_directive(:Directive) is semidet.
 1126%
 1127%   Hook to declare additional directives as safe. The argument is a
 1128%   term `Module:Directive` (without =|:-|= wrapper).  In almost all
 1129%   cases, the implementation must verify that   the `Module` is the
 1130%   current load context as illustrated  below.   This  check is not
 1131%   performed by the system to  allow   for  cases  where particular
 1132%   cross-module directives are allowed.
 1133%
 1134%     ==
 1135%     sandbox:safe_directive(M:Directive) :-
 1136%         prolog_load_context(module, M),
 1137%         ...
 1138%     ==
 1139
 1140
 1141safe_pattr(dynamic(_)).
 1142safe_pattr(thread_local(_)).
 1143safe_pattr(volatile(_)).
 1144safe_pattr(discontiguous(_)).
 1145safe_pattr(multifile(_)).
 1146safe_pattr(public(_)).
 1147safe_pattr(meta_predicate(_)).
 1148safe_pattr(table(_)).
 1149safe_pattr(non_terminal(_)).
 1150
 1151safe_pattr(Var, _) :-
 1152    var(Var),
 1153    !,
 1154    instantiation_error(Var).
 1155safe_pattr((A,B), Attr) :-
 1156    !,
 1157    safe_pattr(A, Attr),
 1158    safe_pattr(B, Attr).
 1159safe_pattr(M:G, Attr) :-
 1160    !,
 1161    (   atom(M),
 1162        prolog_load_context(module, M)
 1163    ->  true
 1164    ;   Goal =.. [Attr,M:G],
 1165        permission_error(directive, sandboxed, (:- Goal))
 1166    ).
 1167safe_pattr(_, _).
 1168
 1169safe_source_directive(op(_,_,Name)) :-
 1170    !,
 1171    (   atom(Name)
 1172    ->  true
 1173    ;   is_list(Name),
 1174        maplist(atom, Name)
 1175    ).
 1176safe_source_directive(set_prolog_flag(Flag, Value)) :-
 1177    !,
 1178    atom(Flag), ground(Value),
 1179    safe_prolog_flag(Flag, Value).
 1180safe_source_directive(style_check(_)).
 1181safe_source_directive(initialization(_)).   % Checked at runtime
 1182safe_source_directive(initialization(_,_)). % Checked at runtime
 1183
 1184directive_loads_file(use_module(library(X)), X).
 1185directive_loads_file(use_module(library(X), _Imports), X).
 1186directive_loads_file(ensure_loaded(library(X)), X).
 1187directive_loads_file(include(X), X).
 1188
 1189safe_path(X) :-
 1190    var(X),
 1191    !,
 1192    instantiation_error(X).
 1193safe_path(X) :-
 1194    (   atom(X)
 1195    ;   string(X)
 1196    ),
 1197    !,
 1198    \+ sub_atom(X, 0, _, 0, '..'),
 1199    \+ sub_atom(X, 0, _, _, '/'),
 1200    \+ sub_atom(X, 0, _, _, '../'),
 1201    \+ sub_atom(X, _, _, 0, '/..'),
 1202    \+ sub_atom(X, _, _, _, '/../').
 1203safe_path(A/B) :-
 1204    !,
 1205    safe_path(A),
 1206    safe_path(B).
 1207
 1208
 1209%!  safe_prolog_flag(+Flag, +Value) is det.
 1210%
 1211%   True if it is safe to set the flag Flag to Value.
 1212%
 1213%   @tbd    If we can avoid that files are loaded after changing
 1214%           this flag, we can allow for more flags.  The syntax
 1215%           flags are safe because they are registered with the
 1216%           module.
 1217
 1218% misc
 1219safe_prolog_flag(generate_debug_info, _).
 1220safe_prolog_flag(optimise, _).
 1221safe_prolog_flag(occurs_check, _).
 1222% syntax
 1223safe_prolog_flag(var_prefix, _).
 1224safe_prolog_flag(double_quotes, _).
 1225safe_prolog_flag(back_quotes, _).
 1226safe_prolog_flag(rational_syntax, _).
 1227% arithmetic
 1228safe_prolog_flag(prefer_rationals, _).
 1229safe_prolog_flag(float_overflow, _).
 1230safe_prolog_flag(float_zero_div, _).
 1231safe_prolog_flag(float_undefined, _).
 1232safe_prolog_flag(float_underflow, _).
 1233safe_prolog_flag(float_rounding, _).
 1234safe_prolog_flag(float_rounding, _).
 1235safe_prolog_flag(max_rational_size, _).
 1236safe_prolog_flag(max_rational_size_action, _).
 1237% tabling
 1238safe_prolog_flag(max_answers_for_subgoal,_).
 1239safe_prolog_flag(max_answers_for_subgoal_action,_).
 1240safe_prolog_flag(max_table_answer_size,_).
 1241safe_prolog_flag(max_table_answer_size_action,_).
 1242safe_prolog_flag(max_table_subgoal_size,_).
 1243safe_prolog_flag(max_table_subgoal_size_action,_).
 1244
 1245
 1246%!  prolog:sandbox_allowed_expansion(:G) is det.
 1247%
 1248%   Throws an exception if G  is   not  considered  a safe expansion
 1249%   goal. This deals with call-backs from the compiler for
 1250%
 1251%     - goal_expansion/2
 1252%     - term_expansion/2
 1253%     - Quasi quotations.
 1254%
 1255%   Our assumption is that external expansion rules are coded safely
 1256%   and we only need to be  careful   if  the sandboxed code defines
 1257%   expansion rules.
 1258
 1259prolog:sandbox_allowed_expansion(M:G) :-
 1260    prolog_load_context(module, M),
 1261    !,
 1262    debug(sandbox(expansion), 'Expand in ~p: ~p', [M, G]),
 1263    safe_goal(M:G).
 1264prolog:sandbox_allowed_expansion(_,_).
 1265
 1266%!  prolog:sandbox_allowed_goal(:G) is det.
 1267%
 1268%   Throw an exception if it is not safe to call G
 1269
 1270prolog:sandbox_allowed_goal(G) :-
 1271    safe_goal(G).
 1272
 1273
 1274                 /*******************************
 1275                 *            MESSAGES          *
 1276                 *******************************/
 1277
 1278:- multifile
 1279    prolog:message//1,
 1280    prolog:message_context//1,
 1281    prolog:error_message//1. 1282
 1283prolog:message(error(instantiation_error, Context)) -->
 1284    { nonvar(Context),
 1285      Context = sandbox(_Goal,Parents),
 1286      numbervars(Context, 1, _)
 1287    },
 1288    [ 'Sandbox restriction!'-[], nl,
 1289      'Could not derive which predicate may be called from'-[]
 1290    ],
 1291    (   { Parents == [] }
 1292    ->  [ 'Search space too large'-[] ]
 1293    ;   callers(Parents, 10)
 1294    ).
 1295
 1296prolog:message_context(sandbox(_G, [])) --> !.
 1297prolog:message_context(sandbox(_G, Parents)) -->
 1298    [ nl, 'Reachable from:'-[] ],
 1299    callers(Parents, 10).
 1300
 1301callers([], _) --> !.
 1302callers(_,  0) --> !.
 1303callers([G|Parents], Level) -->
 1304    { NextLevel is Level-1
 1305    },
 1306    [ nl, '\t  ~p'-[G] ],
 1307    callers(Parents, NextLevel).
 1308
 1309prolog:message(bad_safe_declaration(Goal, File, Line)) -->
 1310    [ '~w:~d: Invalid safe_primitive/1 declaration: ~p'-
 1311      [File, Line, Goal] ].
 1312
 1313prolog:error_message(format_error(Format, Types, Args)) -->
 1314    format_error(Format, Types, Args).
 1315
 1316format_error(Format, Types, Args) -->
 1317    { length(Types, TypeLen),
 1318      length(Args, ArgsLen),
 1319      (   TypeLen > ArgsLen
 1320      ->  Problem = 'not enough'
 1321      ;   Problem = 'too many'
 1322      )
 1323    },
 1324    [ 'format(~q): ~w arguments (found ~w, need ~w)'-
 1325      [Format, Problem, ArgsLen, TypeLen]
 1326    ]