View source with raw 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-2019, 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:- autoload(library(apply),[maplist/2]).   41:- autoload(library(assoc),[empty_assoc/1,get_assoc/3,put_assoc/4]).   42:- autoload(library(debug),[debug/3,debugging/1]).   43:- autoload(library(error),
   44	    [ must_be/2,
   45	      instantiation_error/1,
   46	      type_error/2,
   47	      permission_error/3
   48	    ]).   49:- autoload(library(lists),[append/3]).   50:- autoload(library(prolog_format),[format_types/2]).   51:- use_module(library(apply_macros),[expand_phrase/2]).   52
   53
   54:- multifile
   55    safe_primitive/1,               % Goal
   56    safe_meta_predicate/1,          % Name/Arity
   57    safe_meta/2,                    % Goal, Calls
   58    safe_meta/3,                    % Goal, Context, Calls
   59    safe_global_variable/1,         % Name
   60    safe_directive/1.               % Module:Goal
   61
   62% :- debug(sandbox).

Sandboxed Prolog code

Prolog is a full-featured Turing complete programming language in which it is easy to write programs that can harm your computer. On the other hand, Prolog is a logic based query language which can be exploited to query data interactively from, e.g., the web. This library provides safe_goal/1, which determines whether it is safe to call its argument.

See also
- http://www.swi-prolog.org/pldoc/package/pengines.html */
To be done
- Handling of ^ and // meta predicates
- Complete set of whitelisted predicates
   78:- meta_predicate
   79    safe_goal(:),
   80    safe_call(0).
 safe_call(:Goal)
Call Goal if it complies with the sandboxing rules. Before calling Goal, it performs expand_goal/2, followed by safe_goal/1. Expanding is done explicitly because situations in which safe_call/1 typically concern goals that are not known at compile time.
See also
- safe_goal/1.
   92safe_call(Goal0) :-
   93    expand_goal(Goal0, Goal),
   94    safe_goal(Goal),
   95    call(Goal).
 safe_goal(:Goal) is det
True if calling Goal provides no security risc. This implies that:
Errors
- instantiation_error if the analysis encounters a term in a callable position that is insufficiently instantiated to determine the predicate called.
- permission_error(call, sandboxed, Goal) if Goal is in the call-tree and not white-listed.
  119safe_goal(M:Goal) :-
  120    empty_assoc(Safe0),
  121    catch(safe(Goal, M, [], Safe0, _), E, true),
  122    !,
  123    nb_delete(sandbox_last_error),
  124    (   var(E)
  125    ->  true
  126    ;   throw(E)
  127    ).
  128safe_goal(_) :-
  129    nb_current(sandbox_last_error, E),
  130    !,
  131    nb_delete(sandbox_last_error),
  132    throw(E).
  133safe_goal(G) :-
  134    debug(sandbox(fail), 'safe_goal/1 failed for ~p', [G]),
  135    throw(error(instantiation_error, sandbox(G, []))).
 safe(+Goal, +Module, +Parents, +Safe0, -Safe) is semidet
Is true if Goal can only call safe code.
  142safe(V, _, Parents, _, _) :-
  143    var(V),
  144    !,
  145    Error = error(instantiation_error, sandbox(V, Parents)),
  146    nb_setval(sandbox_last_error, Error),
  147    throw(Error).
  148safe(M:G, _, Parents, Safe0, Safe) :-
  149    !,
  150    must_be(atom, M),
  151    must_be(callable, G),
  152    known_module(M:G, Parents),
  153    (   predicate_property(M:G, imported_from(M2))
  154    ->  true
  155    ;   M2 = M
  156    ),
  157    (   (   safe_primitive(M2:G)
  158        ;   safe_primitive(G),
  159            predicate_property(G, iso)
  160        )
  161    ->  Safe = Safe0
  162    ;   (   predicate_property(M:G, exported)
  163        ;   predicate_property(M:G, public)
  164        ;   predicate_property(M:G, multifile)
  165        ;   predicate_property(M:G, iso)
  166        ;   memberchk(M:_, Parents)
  167        )
  168    ->  safe(G, M, Parents, Safe0, Safe)
  169    ;   throw(error(permission_error(call, sandboxed, M:G),
  170                    sandbox(M:G, Parents)))
  171    ).
  172safe(G, _, Parents, _, _) :-
  173    debugging(sandbox(show)),
  174    length(Parents, Level),
  175    debug(sandbox(show), '[~D] SAFE ~q?', [Level, G]),
  176    fail.
  177safe(G, _, Parents, Safe, Safe) :-
  178    catch(safe_primitive(G),
  179          error(instantiation_error, _),
  180          rethrow_instantition_error([G|Parents])),
  181    predicate_property(G, iso),
  182    !.
  183safe(G, M, Parents, Safe, Safe) :-
  184    known_module(M:G, Parents),
  185    (   predicate_property(M:G, imported_from(M2))
  186    ->  true
  187    ;   M2 = M
  188    ),
  189    (   catch(safe_primitive(M2:G),
  190              error(instantiation_error, _),
  191              rethrow_instantition_error([M2:G|Parents]))
  192    ;   predicate_property(M2:G, number_of_rules(0))
  193    ),
  194    !.
  195safe(G, M, Parents, Safe0, Safe) :-
  196    predicate_property(G, iso),
  197    safe_meta_call(G, M, Called),
  198    !,
  199    add_iso_parent(G, Parents, Parents1),
  200    safe_list(Called, M, Parents1, Safe0, Safe).
  201safe(G, M, Parents, Safe0, Safe) :-
  202    (   predicate_property(M:G, imported_from(M2))
  203    ->  true
  204    ;   M2 = M
  205    ),
  206    safe_meta_call(M2:G, M, Called),
  207    !,
  208    safe_list(Called, M, Parents, Safe0, Safe).
  209safe(G, M, Parents, Safe0, Safe) :-
  210    goal_id(M:G, Id, Gen),
  211    (   get_assoc(Id, Safe0, _)
  212    ->  Safe = Safe0
  213    ;   put_assoc(Id, Safe0, true, Safe1),
  214        (   Gen == M:G
  215        ->  safe_clauses(Gen, M, [Id|Parents], Safe1, Safe)
  216        ;   catch(safe_clauses(Gen, M, [Id|Parents], Safe1, Safe),
  217                  error(instantiation_error, Ctx),
  218                  unsafe(Parents, Ctx))
  219        )
  220    ),
  221    !.
  222safe(G, M, Parents, _, _) :-
  223    debug(sandbox(fail),
  224          'safe/1 failed for ~p (parents:~p)', [M:G, Parents]),
  225    fail.
  226
  227unsafe(Parents, Var) :-
  228    var(Var),
  229    !,
  230    nb_setval(sandbox_last_error,
  231              error(instantiation_error, sandbox(_, Parents))),
  232    fail.
  233unsafe(_Parents, Ctx) :-
  234    Ctx = sandbox(_,_),
  235    nb_setval(sandbox_last_error,
  236              error(instantiation_error, Ctx)),
  237    fail.
  238
  239rethrow_instantition_error(Parents) :-
  240    throw(error(instantiation_error, sandbox(_, Parents))).
  241
  242safe_clauses(G, M, Parents, Safe0, Safe) :-
  243    predicate_property(M:G, interpreted),
  244    def_module(M:G, MD:QG),
  245    \+ compiled(MD:QG),
  246    !,
  247    findall(Ref-Body, clause(MD:QG, Body, Ref), Bodies),
  248    safe_bodies(Bodies, MD, Parents, Safe0, Safe).
  249safe_clauses(G, M, [_|Parents], _, _) :-
  250    predicate_property(M:G, visible),
  251    !,
  252    throw(error(permission_error(call, sandboxed, G),
  253                sandbox(M:G, Parents))).
  254safe_clauses(_, _, [G|Parents], _, _) :-
  255    throw(error(existence_error(procedure, G),
  256                sandbox(G, Parents))).
  257
  258compiled(system:(@(_,_))).
  259
  260known_module(M:_, _) :-
  261    current_module(M),
  262    !.
  263known_module(M:G, Parents) :-
  264    throw(error(permission_error(call, sandboxed, M:G),
  265                sandbox(M:G, Parents))).
  266
  267add_iso_parent(G, Parents, Parents) :-
  268    is_control(G),
  269    !.
  270add_iso_parent(G, Parents, [G|Parents]).
  271
  272is_control((_,_)).
  273is_control((_;_)).
  274is_control((_->_)).
  275is_control((_*->_)).
  276is_control(\+(_)).
 safe_bodies(+Bodies, +Module, +Parents, +Safe0, -Safe)
Verify the safety of bodies. If a clause was compiled with a qualified module, we consider execution of the body in a different module not a cross-module call.
  285safe_bodies([], _, _, Safe, Safe).
  286safe_bodies([Ref-H|T], M, Parents, Safe0, Safe) :-
  287    (   H = M2:H2, nonvar(M2),
  288        clause_property(Ref, module(M2))
  289    ->  copy_term(H2, H3),
  290        CM = M2
  291    ;   copy_term(H, H3),
  292        CM = M
  293    ),
  294    safe(H3, CM, Parents, Safe0, Safe1),
  295    safe_bodies(T, M, Parents, Safe1, Safe).
  296
  297def_module(M:G, MD:QG) :-
  298    predicate_property(M:G, imported_from(MD)),
  299    !,
  300    meta_qualify(MD:G, M, QG).
  301def_module(M:G, M:QG) :-
  302    meta_qualify(M:G, M, QG).
 safe_list(+Called, +Module, +Parents, +Safe0, -Safe)
Processed objects called through meta predicates. If the called object is in our current context we remove the module qualification to avoid the cross-module check.
  310safe_list([], _, _, Safe, Safe).
  311safe_list([H|T], M, Parents, Safe0, Safe) :-
  312    (   H = M2:H2,
  313        M == M2                             % in our context
  314    ->  copy_term(H2, H3)
  315    ;   copy_term(H, H3)                    % cross-module call
  316    ),
  317    safe(H3, M, Parents, Safe0, Safe1),
  318    safe_list(T, M, Parents, Safe1, Safe).
 meta_qualify(:G, +M, -QG) is det
Perform meta-qualification of the goal-argument
  324meta_qualify(MD:G, M, QG) :-
  325    predicate_property(MD:G, meta_predicate(Head)),
  326    !,
  327    G =.. [Name|Args],
  328    Head =.. [_|Q],
  329    qualify_args(Q, M, Args, QArgs),
  330    QG =.. [Name|QArgs].
  331meta_qualify(_:G, _, G).
  332
  333qualify_args([], _, [], []).
  334qualify_args([H|T], M, [A|AT], [Q|QT]) :-
  335    qualify_arg(H, M, A, Q),
  336    qualify_args(T, M, AT, QT).
  337
  338qualify_arg(S, M, A, Q) :-
  339    q_arg(S),
  340    !,
  341    qualify(A, M, Q).
  342qualify_arg(_, _, A, A).
  343
  344q_arg(I) :- integer(I), !.
  345q_arg(:).
  346q_arg(^).
  347q_arg(//).
  348
  349qualify(A, M, MZ:Q) :-
  350    strip_module(M:A, MZ, Q).
 goal_id(:Goal, -Id, -Gen) is nondet
Generate an identifier for the goal proven to be safe. We first try to prove the most general form of the goal. If this fails, we try to prove more specific versions.
To be done
- Do step-by-step generalisation instead of the current two levels (most general and most specific).
- We could also use variant_sha1 for the goal ids.
  362goal_id(M:Goal, M:Id, Gen) :-
  363    !,
  364    goal_id(Goal, Id, Gen).
  365goal_id(Var, _, _) :-
  366    var(Var),
  367    !,
  368    instantiation_error(Var).
  369goal_id(Atom, Atom, Atom) :-
  370    atom(Atom),
  371    !.
  372goal_id(Term, _, _) :-
  373    \+ compound(Term),
  374    !,
  375    type_error(callable, Term).
  376goal_id(Term, Skolem, Gen) :-           % most general form
  377    compound_name_arity(Term, Name, Arity),
  378    compound_name_arity(Skolem, Name, Arity),
  379    compound_name_arity(Gen, Name, Arity),
  380    copy_goal_args(1, Term, Skolem, Gen),
  381    (   Gen =@= Term
  382    ->  !                           % No more specific one; we can commit
  383    ;   true
  384    ),
  385    numbervars(Skolem, 0, _).
  386goal_id(Term, Skolem, Term) :-          % most specific form
  387    debug(sandbox(specify), 'Retrying with ~p', [Term]),
  388    copy_term(Term, Skolem),
  389    numbervars(Skolem, 0, _).
 copy_goal_args(+I, +Term, +Skolem, +Gen) is det
Create the most general form, but keep module qualified arguments because they will likely be called anyway.
  396copy_goal_args(I, Term, Skolem, Gen) :-
  397    arg(I, Term, TA),
  398    !,
  399    arg(I, Skolem, SA),
  400    arg(I, Gen, GA),
  401    copy_goal_arg(TA, SA, GA),
  402    I2 is I + 1,
  403    copy_goal_args(I2, Term, Skolem, Gen).
  404copy_goal_args(_, _, _, _).
  405
  406copy_goal_arg(Arg, SArg, Arg) :-
  407    copy_goal_arg(Arg),
  408    !,
  409    copy_term(Arg, SArg).
  410copy_goal_arg(_, _, _).
  411
  412copy_goal_arg(Var) :- var(Var), !, fail.
  413copy_goal_arg(_:_).
 verify_safe_declaration(+Decl)
See whether a safe declaration makes sense. That is, the predicate must be defined (such that the attacker cannot define the predicate), must be sufficiently instantiated and only ISO declared predicates may omit a module qualification.
To be done
- Verify safe_meta/2 declarations. It is a bit less clear what the rules are.
  425term_expansion(safe_primitive(Goal), Term) :-
  426    (   verify_safe_declaration(Goal)
  427    ->  Term = safe_primitive(Goal)
  428    ;   Term = []
  429    ).
  430
  431system:term_expansion(sandbox:safe_primitive(Goal), Term) :-
  432    \+ current_prolog_flag(xref, true),
  433    (   verify_safe_declaration(Goal)
  434    ->  Term = sandbox:safe_primitive(Goal)
  435    ;   Term = []
  436    ).
  437
  438verify_safe_declaration(Var) :-
  439    var(Var),
  440    !,
  441    instantiation_error(Var).
  442verify_safe_declaration(Module:Goal) :-
  443    !,
  444    must_be(atom, Module),
  445    must_be(callable, Goal),
  446    (   ok_meta(Module:Goal)
  447    ->  true
  448    ;   (   predicate_property(Module:Goal, visible)
  449        ->  true
  450        ;   predicate_property(Module:Goal, foreign)
  451        ),
  452        \+ predicate_property(Module:Goal, imported_from(_)),
  453        \+ predicate_property(Module:Goal, meta_predicate(_))
  454    ->  true
  455    ;   permission_error(declare, safe_goal, Module:Goal)
  456    ).
  457verify_safe_declaration(Goal) :-
  458    must_be(callable, Goal),
  459    (   predicate_property(system:Goal, iso),
  460        \+ predicate_property(system:Goal, meta_predicate())
  461    ->  true
  462    ;   permission_error(declare, safe_goal, Goal)
  463    ).
  464
  465ok_meta(system:assert(_)).
  466ok_meta(system:use_module(_,_)).
  467ok_meta(system:use_module(_)).
  468
  469verify_predefined_safe_declarations :-
  470    forall(clause(safe_primitive(Goal), _Body, Ref),
  471           ( catch(verify_safe_declaration(Goal), E, true),
  472             (   nonvar(E)
  473             ->  clause_property(Ref, file(File)),
  474                 clause_property(Ref, line_count(Line)),
  475                 print_message(error, bad_safe_declaration(Goal, File, Line))
  476             ;   true
  477             )
  478           )).
  479
  480:- initialization(verify_predefined_safe_declarations, now).
 safe_primitive(?Goal) is nondet
True if Goal is safe to call (i.e., cannot access dangerous system-resources and cannot upset other parts of the Prolog process). There are two types of facts. ISO built-ins are declared without a module prefix. This is safe because it is not allowed to (re-)define these primitives (i.e., give them an unsafe implementation) and the way around (redefine_system_predicate/1) is unsafe. The other group are module-qualified and only match if the system infers that the predicate is imported from the given module.
  494% First, all ISO system predicates that are considered safe
  495
  496safe_primitive(true).
  497safe_primitive(fail).
  498safe_primitive(system:false).
  499safe_primitive(repeat).
  500safe_primitive(!).
  501                                        % types
  502safe_primitive(var(_)).
  503safe_primitive(nonvar(_)).
  504safe_primitive(system:attvar(_)).
  505safe_primitive(integer(_)).
  506safe_primitive(float(_)).
  507safe_primitive(system:rational(_)).
  508safe_primitive(number(_)).
  509safe_primitive(atom(_)).
  510safe_primitive(system:blob(_,_)).
  511safe_primitive(system:string(_)).
  512safe_primitive(atomic(_)).
  513safe_primitive(compound(_)).
  514safe_primitive(callable(_)).
  515safe_primitive(ground(_)).
  516safe_primitive(system:cyclic_term(_)).
  517safe_primitive(acyclic_term(_)).
  518safe_primitive(system:is_stream(_)).
  519safe_primitive(system:'$is_char'(_)).
  520safe_primitive(system:'$is_char_code'(_)).
  521safe_primitive(system:'$is_char_list'(_,_)).
  522safe_primitive(system:'$is_code_list'(_,_)).
  523                                        % ordering
  524safe_primitive(@>(_,_)).
  525safe_primitive(@>=(_,_)).
  526safe_primitive(==(_,_)).
  527safe_primitive(@<(_,_)).
  528safe_primitive(@=<(_,_)).
  529safe_primitive(compare(_,_,_)).
  530safe_primitive(sort(_,_)).
  531safe_primitive(keysort(_,_)).
  532safe_primitive(system: =@=(_,_)).
  533safe_primitive(system:'$btree_find_node'(_,_,_,_,_)).
  534
  535                                        % unification and equivalence
  536safe_primitive(=(_,_)).
  537safe_primitive(\=(_,_)).
  538safe_primitive(system:'?='(_,_)).
  539safe_primitive(system:unifiable(_,_,_)).
  540safe_primitive(unify_with_occurs_check(_,_)).
  541safe_primitive(\==(_,_)).
  542                                        % arithmetic
  543safe_primitive(is(_,_)).
  544safe_primitive(>(_,_)).
  545safe_primitive(>=(_,_)).
  546safe_primitive(=:=(_,_)).
  547safe_primitive(=\=(_,_)).
  548safe_primitive(=<(_,_)).
  549safe_primitive(<(_,_)).
  550:- if(current_prolog_flag(bounded, false)).  551safe_primitive(system:nth_integer_root_and_remainder(_,_,_,_)).
  552:- endif.  553
  554                                        % term-handling
  555safe_primitive(arg(_,_,_)).
  556safe_primitive(system:setarg(_,_,_)).
  557safe_primitive(system:nb_setarg(_,_,_)).
  558safe_primitive(system:nb_linkarg(_,_,_)).
  559safe_primitive(functor(_,_,_)).
  560safe_primitive(_ =.. _).
  561safe_primitive(system:compound_name_arity(_,_,_)).
  562safe_primitive(system:compound_name_arguments(_,_,_)).
  563safe_primitive(system:'$filled_array'(_,_,_,_)).
  564safe_primitive(copy_term(_,_)).
  565safe_primitive(system:duplicate_term(_,_)).
  566safe_primitive(system:copy_term_nat(_,_)).
  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).
 safe_assert(+Term) is semidet
True if assert(Term) is safe, which means it asserts in the current module. Cross-module asserts are considered unsafe. We only allow for adding facts. In theory, we could also allow for rules if we prove the safety of the body.
  794safe_assert(C) :- cyclic_term(C), !, fail.
  795safe_assert(X) :- var(X), !, fail.
  796safe_assert(_Head:-_Body) :- !, fail.
  797safe_assert(_:_) :- !, fail.
  798safe_assert(_).
 safe_clause(+Head) is semidet
Consider a call to clause safe if it does not try to cross a module boundary. Cross-module usage of clause/2 can extract private information from other modules.
  806safe_clause(H) :- var(H), !.
  807safe_clause(_:_) :- !, fail.
  808safe_clause(_).
 safe_global_var(+Name) is semidet
True if Name is a global variable to which assertion is considered safe.
  816safe_global_var(Name) :-
  817    var(Name),
  818    !,
  819    instantiation_error(Name).
  820safe_global_var(Name) :-
  821    safe_global_variable(Name).
 safe_global_variable(Name) is semidet
Declare the given global variable safe to write to.
 safe_meta(+Goal, -Called:list(callable)) is semidet
Hook. True if Goal is a meta-predicate that is considered safe iff all elements in Called are safe.
  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 = _:_.
 attr_hook_predicates(+Hooks0, +Module, -Hooks) is det
Filter the defined hook implementations. This is safe because (1) calling an undefined predicate is not a safety issue, (2) the user an only assert in the current module and only predicates that have a safe body. This avoids the need to define attribute hooks solely for the purpose of making them safe.
  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).
 expand_nt(+NT, ?Xs0, ?Xs, -NewGoal)
Similar to expand_phrase/2, but we do throw errors instead of failing if NT is not sufficiently instantiated.
  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    ).
 safe_meta_call(+Goal, +Context, -Called:list(callable)) is semidet
True if Goal is a meta-predicate that is considered safe iff all elements in Called are safe.
  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).
 safe_meta(?Template)
 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,*,*)).
 safe_output(+Output)
True if something is a safe output argument for with_output_to/2 and friends. We do not want writing to streams.
 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).
 format_calls(+Format, +FormatArgs, -Calls)
Find ~@ calls from Format and Args.
 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.
 prolog:sandbox_allowed_directive(:G) is det
Throws an exception if G is not considered a safe directive.
 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).
 safe_directive(:Directive) is semidet
Hook to declare additional directives as safe. The argument is a term Module:Directive (without :- wrapper). In almost all cases, the implementation must verify that the Module is the current load context as illustrated below. This check is not performed by the system to allow for cases where particular cross-module directives are allowed.
sandbox:safe_directive(M:Directive) :-
    prolog_load_context(module, M),
    ...
 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(_)).
 1149
 1150safe_pattr(Var, _) :-
 1151    var(Var),
 1152    !,
 1153    instantiation_error(Var).
 1154safe_pattr((A,B), Attr) :-
 1155    !,
 1156    safe_pattr(A, Attr),
 1157    safe_pattr(B, Attr).
 1158safe_pattr(M:G, Attr) :-
 1159    !,
 1160    (   atom(M),
 1161        prolog_load_context(module, M)
 1162    ->  true
 1163    ;   Goal =.. [Attr,M:G],
 1164        permission_error(directive, sandboxed, (:- Goal))
 1165    ).
 1166safe_pattr(_, _).
 1167
 1168safe_source_directive(op(_,_,Name)) :-
 1169    !,
 1170    (   atom(Name)
 1171    ->  true
 1172    ;   is_list(Name),
 1173        maplist(atom, Name)
 1174    ).
 1175safe_source_directive(set_prolog_flag(Flag, Value)) :-
 1176    !,
 1177    atom(Flag), ground(Value),
 1178    safe_prolog_flag(Flag, Value).
 1179safe_source_directive(style_check(_)).
 1180safe_source_directive(initialization(_)).   % Checked at runtime
 1181safe_source_directive(initialization(_,_)). % Checked at runtime
 1182
 1183directive_loads_file(use_module(library(X)), X).
 1184directive_loads_file(use_module(library(X), _Imports), X).
 1185directive_loads_file(ensure_loaded(library(X)), X).
 1186directive_loads_file(include(X), X).
 1187
 1188safe_path(X) :-
 1189    var(X),
 1190    !,
 1191    instantiation_error(X).
 1192safe_path(X) :-
 1193    (   atom(X)
 1194    ;   string(X)
 1195    ),
 1196    !,
 1197    \+ sub_atom(X, 0, _, 0, '..'),
 1198    \+ sub_atom(X, 0, _, _, '/'),
 1199    \+ sub_atom(X, 0, _, _, '../'),
 1200    \+ sub_atom(X, _, _, 0, '/..'),
 1201    \+ sub_atom(X, _, _, _, '/../').
 1202safe_path(A/B) :-
 1203    !,
 1204    safe_path(A),
 1205    safe_path(B).
 safe_prolog_flag(+Flag, +Value) is det
True if it is safe to set the flag Flag to Value.
To be done
- If we can avoid that files are loaded after changing this flag, we can allow for more flags. The syntax flags are safe because they are registered with the module.
 1217% misc
 1218safe_prolog_flag(generate_debug_info, _).
 1219safe_prolog_flag(optimise, _).
 1220safe_prolog_flag(occurs_check, _).
 1221% syntax
 1222safe_prolog_flag(var_prefix, _).
 1223safe_prolog_flag(double_quotes, _).
 1224safe_prolog_flag(back_quotes, _).
 1225safe_prolog_flag(rational_syntax, _).
 1226% arithmetic
 1227safe_prolog_flag(prefer_rationals, _).
 1228safe_prolog_flag(float_overflow, _).
 1229safe_prolog_flag(float_zero_div, _).
 1230safe_prolog_flag(float_undefined, _).
 1231safe_prolog_flag(float_underflow, _).
 1232safe_prolog_flag(float_rounding, _).
 1233safe_prolog_flag(float_rounding, _).
 1234safe_prolog_flag(max_rational_size, _).
 1235safe_prolog_flag(max_rational_size_action, _).
 1236% tabling
 1237safe_prolog_flag(max_answers_for_subgoal,_).
 1238safe_prolog_flag(max_answers_for_subgoal_action,_).
 prolog:sandbox_allowed_expansion(:G) is det
Throws an exception if G is not considered a safe expansion goal. This deals with call-backs from the compiler for

Our assumption is that external expansion rules are coded safely and we only need to be careful if the sandboxed code defines expansion rules.

 1254prolog:sandbox_allowed_expansion(M:G) :-
 1255    prolog_load_context(module, M),
 1256    !,
 1257    debug(sandbox(expansion), 'Expand in ~p: ~p', [M, G]),
 1258    safe_goal(M:G).
 1259prolog:sandbox_allowed_expansion(_,_).
 prolog:sandbox_allowed_goal(:G) is det
Throw an exception if it is not safe to call G
 1265prolog:sandbox_allowed_goal(G) :-
 1266    safe_goal(G).
 1267
 1268
 1269                 /*******************************
 1270                 *            MESSAGES          *
 1271                 *******************************/
 1272
 1273:- multifile
 1274    prolog:message//1,
 1275    prolog:message_context//1,
 1276    prolog:error_message//1. 1277
 1278prolog:message(error(instantiation_error, Context)) -->
 1279    { nonvar(Context),
 1280      Context = sandbox(_Goal,Parents),
 1281      numbervars(Context, 1, _)
 1282    },
 1283    [ 'Sandbox restriction!'-[], nl,
 1284      'Could not derive which predicate may be called from'-[]
 1285    ],
 1286    (   { Parents == [] }
 1287    ->  [ 'Search space too large'-[] ]
 1288    ;   callers(Parents, 10)
 1289    ).
 1290
 1291prolog:message_context(sandbox(_G, [])) --> !.
 1292prolog:message_context(sandbox(_G, Parents)) -->
 1293    [ nl, 'Reachable from:'-[] ],
 1294    callers(Parents, 10).
 1295
 1296callers([], _) --> !.
 1297callers(_,  0) --> !.
 1298callers([G|Parents], Level) -->
 1299    { NextLevel is Level-1
 1300    },
 1301    [ nl, '\t  ~p'-[G] ],
 1302    callers(Parents, NextLevel).
 1303
 1304prolog:message(bad_safe_declaration(Goal, File, Line)) -->
 1305    [ '~w:~d: Invalid safe_primitive/1 declaration: ~p'-
 1306      [File, Line, Goal] ].
 1307
 1308prolog:error_message(format_error(Format, Types, Args)) -->
 1309    format_error(Format, Types, Args).
 1310
 1311format_error(Format, Types, Args) -->
 1312    { length(Types, TypeLen),
 1313      length(Args, ArgsLen),
 1314      (   TypeLen > ArgsLen
 1315      ->  Problem = 'not enough'
 1316      ;   Problem = 'too many'
 1317      )
 1318    },
 1319    [ 'format(~q): ~w arguments (found ~w, need ~w)'-
 1320      [Format, Problem, ArgsLen, TypeLen]
 1321    ]