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:- use_module(library(assoc)).   41:- use_module(library(lists)).   42:- use_module(library(debug)).   43:- use_module(library(error)).   44:- use_module(library(prolog_format)).   45:- use_module(library(apply)).   46
   47:- multifile
   48    safe_primitive/1,               % Goal
   49    safe_meta_predicate/1,          % Name/Arity
   50    safe_meta/2,                    % Goal, Calls
   51    safe_meta/3,                    % Goal, Context, Calls
   52    safe_global_variable/1,         % Name
   53    safe_directive/1.               % Module:Goal
   54
   55% :- 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
   71:- meta_predicate
   72    safe_goal(:),
   73    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.
   85safe_call(Goal0) :-
   86    expand_goal(Goal0, Goal),
   87    safe_goal(Goal),
   88    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.
  112safe_goal(M:Goal) :-
  113    empty_assoc(Safe0),
  114    catch(safe(Goal, M, [], Safe0, _), E, true),
  115    !,
  116    nb_delete(sandbox_last_error),
  117    (   var(E)
  118    ->  true
  119    ;   throw(E)
  120    ).
  121safe_goal(_) :-
  122    nb_current(sandbox_last_error, E),
  123    !,
  124    nb_delete(sandbox_last_error),
  125    throw(E).
  126safe_goal(G) :-
  127    debug(sandbox(fail), 'safe_goal/1 failed for ~p', [G]),
  128    throw(error(instantiation_error, sandbox(G, []))).
 safe(+Goal, +Module, +Parents, +Safe0, -Safe) is semidet
Is true if Goal can only call safe code.
  135safe(V, _, Parents, _, _) :-
  136    var(V),
  137    !,
  138    Error = error(instantiation_error, sandbox(V, Parents)),
  139    nb_setval(sandbox_last_error, Error),
  140    throw(Error).
  141safe(M:G, _, Parents, Safe0, Safe) :-
  142    !,
  143    must_be(atom, M),
  144    must_be(callable, G),
  145    known_module(M:G, Parents),
  146    (   predicate_property(M:G, imported_from(M2))
  147    ->  true
  148    ;   M2 = M
  149    ),
  150    (   (   safe_primitive(M2:G)
  151        ;   safe_primitive(G),
  152            predicate_property(G, iso)
  153        )
  154    ->  Safe = Safe0
  155    ;   (   predicate_property(M:G, exported)
  156        ;   predicate_property(M:G, public)
  157        ;   predicate_property(M:G, multifile)
  158        ;   predicate_property(M:G, iso)
  159        ;   memberchk(M:_, Parents)
  160        )
  161    ->  safe(G, M, Parents, Safe0, Safe)
  162    ;   throw(error(permission_error(call, sandboxed, M:G),
  163                    sandbox(M:G, Parents)))
  164    ).
  165safe(G, _, Parents, _, _) :-
  166    debugging(sandbox(show)),
  167    length(Parents, Level),
  168    debug(sandbox(show), '[~D] SAFE ~q?', [Level, G]),
  169    fail.
  170safe(G, _, Parents, Safe, Safe) :-
  171    catch(safe_primitive(G),
  172          error(instantiation_error, _),
  173          rethrow_instantition_error([G|Parents])),
  174    predicate_property(G, iso),
  175    !.
  176safe(G, M, Parents, Safe, Safe) :-
  177    known_module(M:G, Parents),
  178    (   predicate_property(M:G, imported_from(M2))
  179    ->  true
  180    ;   M2 = M
  181    ),
  182    (   catch(safe_primitive(M2:G),
  183              error(instantiation_error, _),
  184              rethrow_instantition_error([M2:G|Parents]))
  185    ;   predicate_property(M2:G, number_of_rules(0))
  186    ),
  187    !.
  188safe(G, M, Parents, Safe0, Safe) :-
  189    predicate_property(G, iso),
  190    safe_meta_call(G, M, Called),
  191    !,
  192    add_iso_parent(G, Parents, Parents1),
  193    safe_list(Called, M, Parents1, Safe0, Safe).
  194safe(G, M, Parents, Safe0, Safe) :-
  195    (   predicate_property(M:G, imported_from(M2))
  196    ->  true
  197    ;   M2 = M
  198    ),
  199    safe_meta_call(M2:G, M, Called),
  200    !,
  201    safe_list(Called, M, Parents, Safe0, Safe).
  202safe(G, M, Parents, Safe0, Safe) :-
  203    goal_id(M:G, Id, Gen),
  204    (   get_assoc(Id, Safe0, _)
  205    ->  Safe = Safe0
  206    ;   put_assoc(Id, Safe0, true, Safe1),
  207        (   Gen == M:G
  208        ->  safe_clauses(Gen, M, [Id|Parents], Safe1, Safe)
  209        ;   catch(safe_clauses(Gen, M, [Id|Parents], Safe1, Safe),
  210                  error(instantiation_error, Ctx),
  211                  unsafe(Parents, Ctx))
  212        )
  213    ),
  214    !.
  215safe(G, M, Parents, _, _) :-
  216    debug(sandbox(fail),
  217          'safe/1 failed for ~p (parents:~p)', [M:G, Parents]),
  218    fail.
  219
  220unsafe(Parents, Var) :-
  221    var(Var),
  222    !,
  223    nb_setval(sandbox_last_error,
  224              error(instantiation_error, sandbox(_, Parents))),
  225    fail.
  226unsafe(_Parents, Ctx) :-
  227    Ctx = sandbox(_,_),
  228    nb_setval(sandbox_last_error,
  229              error(instantiation_error, Ctx)),
  230    fail.
  231
  232rethrow_instantition_error(Parents) :-
  233    throw(error(instantiation_error, sandbox(_, Parents))).
  234
  235safe_clauses(G, M, Parents, Safe0, Safe) :-
  236    predicate_property(M:G, interpreted),
  237    def_module(M:G, MD:QG),
  238    \+ compiled(MD:QG),
  239    !,
  240    findall(Ref-Body, clause(MD:QG, Body, Ref), Bodies),
  241    safe_bodies(Bodies, MD, Parents, Safe0, Safe).
  242safe_clauses(G, M, [_|Parents], _, _) :-
  243    predicate_property(M:G, visible),
  244    !,
  245    throw(error(permission_error(call, sandboxed, G),
  246                sandbox(M:G, Parents))).
  247safe_clauses(_, _, [G|Parents], _, _) :-
  248    throw(error(existence_error(procedure, G),
  249                sandbox(G, Parents))).
  250
  251compiled(system:(@(_,_))).
  252
  253known_module(M:_, _) :-
  254    current_module(M),
  255    !.
  256known_module(M:G, Parents) :-
  257    throw(error(permission_error(call, sandboxed, M:G),
  258                sandbox(M:G, Parents))).
  259
  260add_iso_parent(G, Parents, Parents) :-
  261    is_control(G),
  262    !.
  263add_iso_parent(G, Parents, [G|Parents]).
  264
  265is_control((_,_)).
  266is_control((_;_)).
  267is_control((_->_)).
  268is_control((_*->_)).
  269is_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.
  278safe_bodies([], _, _, Safe, Safe).
  279safe_bodies([Ref-H|T], M, Parents, Safe0, Safe) :-
  280    (   H = M2:H2, nonvar(M2),
  281        clause_property(Ref, module(M2))
  282    ->  copy_term(H2, H3),
  283        CM = M2
  284    ;   copy_term(H, H3),
  285        CM = M
  286    ),
  287    safe(H3, CM, Parents, Safe0, Safe1),
  288    safe_bodies(T, M, Parents, Safe1, Safe).
  289
  290def_module(M:G, MD:QG) :-
  291    predicate_property(M:G, imported_from(MD)),
  292    !,
  293    meta_qualify(MD:G, M, QG).
  294def_module(M:G, M:QG) :-
  295    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.
  303safe_list([], _, _, Safe, Safe).
  304safe_list([H|T], M, Parents, Safe0, Safe) :-
  305    (   H = M2:H2,
  306        M == M2                             % in our context
  307    ->  copy_term(H2, H3)
  308    ;   copy_term(H, H3)                    % cross-module call
  309    ),
  310    safe(H3, M, Parents, Safe0, Safe1),
  311    safe_list(T, M, Parents, Safe1, Safe).
 meta_qualify(:G, +M, -QG) is det
Perform meta-qualification of the goal-argument
  317meta_qualify(MD:G, M, QG) :-
  318    predicate_property(MD:G, meta_predicate(Head)),
  319    !,
  320    G =.. [Name|Args],
  321    Head =.. [_|Q],
  322    qualify_args(Q, M, Args, QArgs),
  323    QG =.. [Name|QArgs].
  324meta_qualify(_:G, _, G).
  325
  326qualify_args([], _, [], []).
  327qualify_args([H|T], M, [A|AT], [Q|QT]) :-
  328    qualify_arg(H, M, A, Q),
  329    qualify_args(T, M, AT, QT).
  330
  331qualify_arg(S, M, A, Q) :-
  332    q_arg(S),
  333    !,
  334    qualify(A, M, Q).
  335qualify_arg(_, _, A, A).
  336
  337q_arg(I) :- integer(I), !.
  338q_arg(:).
  339q_arg(^).
  340q_arg(//).
  341
  342qualify(A, M, MZ:Q) :-
  343    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.
  355goal_id(M:Goal, M:Id, Gen) :-
  356    !,
  357    goal_id(Goal, Id, Gen).
  358goal_id(Var, _, _) :-
  359    var(Var),
  360    !,
  361    instantiation_error(Var).
  362goal_id(Atom, Atom, Atom) :-
  363    atom(Atom),
  364    !.
  365goal_id(Term, _, _) :-
  366    \+ compound(Term),
  367    !,
  368    type_error(callable, Term).
  369goal_id(Term, Skolem, Gen) :-           % most general form
  370    compound_name_arity(Term, Name, Arity),
  371    compound_name_arity(Skolem, Name, Arity),
  372    compound_name_arity(Gen, Name, Arity),
  373    copy_goal_args(1, Term, Skolem, Gen),
  374    (   Gen =@= Term
  375    ->  !                           % No more specific one; we can commit
  376    ;   true
  377    ),
  378    numbervars(Skolem, 0, _).
  379goal_id(Term, Skolem, Term) :-          % most specific form
  380    debug(sandbox(specify), 'Retrying with ~p', [Term]),
  381    copy_term(Term, Skolem),
  382    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.
  389copy_goal_args(I, Term, Skolem, Gen) :-
  390    arg(I, Term, TA),
  391    !,
  392    arg(I, Skolem, SA),
  393    arg(I, Gen, GA),
  394    copy_goal_arg(TA, SA, GA),
  395    I2 is I + 1,
  396    copy_goal_args(I2, Term, Skolem, Gen).
  397copy_goal_args(_, _, _, _).
  398
  399copy_goal_arg(Arg, SArg, Arg) :-
  400    copy_goal_arg(Arg),
  401    !,
  402    copy_term(Arg, SArg).
  403copy_goal_arg(_, _, _).
  404
  405copy_goal_arg(Var) :- var(Var), !, fail.
  406copy_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.
  418term_expansion(safe_primitive(Goal), Term) :-
  419    (   verify_safe_declaration(Goal)
  420    ->  Term = safe_primitive(Goal)
  421    ;   Term = []
  422    ).
  423
  424system:term_expansion(sandbox:safe_primitive(Goal), Term) :-
  425    \+ current_prolog_flag(xref, true),
  426    (   verify_safe_declaration(Goal)
  427    ->  Term = sandbox:safe_primitive(Goal)
  428    ;   Term = []
  429    ).
  430
  431verify_safe_declaration(Var) :-
  432    var(Var),
  433    !,
  434    instantiation_error(Var).
  435verify_safe_declaration(Module:Goal) :-
  436    !,
  437    must_be(atom, Module),
  438    must_be(callable, Goal),
  439    (   ok_meta(Module:Goal)
  440    ->  true
  441    ;   (   predicate_property(Module:Goal, visible)
  442        ->  true
  443        ;   predicate_property(Module:Goal, foreign)
  444        ),
  445        \+ predicate_property(Module:Goal, imported_from(_)),
  446        \+ predicate_property(Module:Goal, meta_predicate(_))
  447    ->  true
  448    ;   permission_error(declare, safe_goal, Module:Goal)
  449    ).
  450verify_safe_declaration(Goal) :-
  451    must_be(callable, Goal),
  452    (   predicate_property(system:Goal, iso),
  453        \+ predicate_property(system:Goal, meta_predicate())
  454    ->  true
  455    ;   permission_error(declare, safe_goal, Goal)
  456    ).
  457
  458ok_meta(system:assert(_)).
  459ok_meta(system:use_module(_,_)).
  460ok_meta(system:use_module(_)).
  461
  462verify_predefined_safe_declarations :-
  463    forall(clause(safe_primitive(Goal), _Body, Ref),
  464           ( catch(verify_safe_declaration(Goal), E, true),
  465             (   nonvar(E)
  466             ->  clause_property(Ref, file(File)),
  467                 clause_property(Ref, line_count(Line)),
  468                 print_message(error, bad_safe_declaration(Goal, File, Line))
  469             ;   true
  470             )
  471           )).
  472
  473:- 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.
  487% First, all ISO system predicates that are considered safe
  488
  489safe_primitive(true).
  490safe_primitive(fail).
  491safe_primitive(system:false).
  492safe_primitive(repeat).
  493safe_primitive(!).
  494                                        % types
  495safe_primitive(var(_)).
  496safe_primitive(nonvar(_)).
  497safe_primitive(system:attvar(_)).
  498safe_primitive(integer(_)).
  499safe_primitive(float(_)).
  500safe_primitive(system:rational(_)).
  501safe_primitive(number(_)).
  502safe_primitive(atom(_)).
  503safe_primitive(system:blob(_,_)).
  504safe_primitive(system:string(_)).
  505safe_primitive(atomic(_)).
  506safe_primitive(compound(_)).
  507safe_primitive(callable(_)).
  508safe_primitive(ground(_)).
  509safe_primitive(system:cyclic_term(_)).
  510safe_primitive(acyclic_term(_)).
  511safe_primitive(system:is_stream(_)).
  512safe_primitive(system:'$is_char'(_)).
  513safe_primitive(system:'$is_char_code'(_)).
  514safe_primitive(system:'$is_char_list'(_,_)).
  515safe_primitive(system:'$is_code_list'(_,_)).
  516                                        % ordering
  517safe_primitive(@>(_,_)).
  518safe_primitive(@>=(_,_)).
  519safe_primitive(==(_,_)).
  520safe_primitive(@<(_,_)).
  521safe_primitive(@=<(_,_)).
  522safe_primitive(compare(_,_,_)).
  523safe_primitive(sort(_,_)).
  524safe_primitive(keysort(_,_)).
  525safe_primitive(system: =@=(_,_)).
  526safe_primitive(system:'$btree_find_node'(_,_,_,_,_)).
  527
  528                                        % unification and equivalence
  529safe_primitive(=(_,_)).
  530safe_primitive(\=(_,_)).
  531safe_primitive(system:'?='(_,_)).
  532safe_primitive(system:unifiable(_,_,_)).
  533safe_primitive(unify_with_occurs_check(_,_)).
  534safe_primitive(\==(_,_)).
  535                                        % arithmetic
  536safe_primitive(is(_,_)).
  537safe_primitive(>(_,_)).
  538safe_primitive(>=(_,_)).
  539safe_primitive(=:=(_,_)).
  540safe_primitive(=\=(_,_)).
  541safe_primitive(=<(_,_)).
  542safe_primitive(<(_,_)).
  543safe_primitive(system:nth_integer_root_and_remainder(_,_,_,_)).
  544
  545                                        % term-handling
  546safe_primitive(arg(_,_,_)).
  547safe_primitive(system:setarg(_,_,_)).
  548safe_primitive(system:nb_setarg(_,_,_)).
  549safe_primitive(system:nb_linkarg(_,_,_)).
  550safe_primitive(functor(_,_,_)).
  551safe_primitive(_ =.. _).
  552safe_primitive(system:compound_name_arity(_,_,_)).
  553safe_primitive(system:compound_name_arguments(_,_,_)).
  554safe_primitive(system:'$filled_array'(_,_,_,_)).
  555safe_primitive(copy_term(_,_)).
  556safe_primitive(system:duplicate_term(_,_)).
  557safe_primitive(system:copy_term_nat(_,_)).
  558safe_primitive(numbervars(_,_,_)).
  559safe_primitive(system:numbervars(_,_,_,_)).
  560safe_primitive(subsumes_term(_,_)).
  561safe_primitive(system:term_hash(_,_)).
  562safe_primitive(system:term_hash(_,_,_,_)).
  563safe_primitive(system:variant_sha1(_,_)).
  564safe_primitive(system:variant_hash(_,_)).
  565safe_primitive(system:'$term_size'(_,_,_)).
  566
  567                                        % dicts
  568safe_primitive(system:is_dict(_)).
  569safe_primitive(system:is_dict(_,_)).
  570safe_primitive(system:get_dict(_,_,_)).
  571safe_primitive(system:get_dict(_,_,_,_,_)).
  572safe_primitive(system:'$get_dict_ex'(_,_,_)).
  573safe_primitive(system:dict_create(_,_,_)).
  574safe_primitive(system:dict_pairs(_,_,_)).
  575safe_primitive(system:put_dict(_,_,_)).
  576safe_primitive(system:put_dict(_,_,_,_)).
  577safe_primitive(system:del_dict(_,_,_,_)).
  578safe_primitive(system:select_dict(_,_,_)).
  579safe_primitive(system:b_set_dict(_,_,_)).
  580safe_primitive(system:nb_set_dict(_,_,_)).
  581safe_primitive(system:nb_link_dict(_,_,_)).
  582safe_primitive(system:(:<(_,_))).
  583safe_primitive(system:(>:<(_,_))).
  584                                        % atoms
  585safe_primitive(atom_chars(_, _)).
  586safe_primitive(atom_codes(_, _)).
  587safe_primitive(sub_atom(_,_,_,_,_)).
  588safe_primitive(atom_concat(_,_,_)).
  589safe_primitive(atom_length(_,_)).
  590safe_primitive(char_code(_,_)).
  591safe_primitive(system:name(_,_)).
  592safe_primitive(system:atomic_concat(_,_,_)).
  593safe_primitive(system:atomic_list_concat(_,_)).
  594safe_primitive(system:atomic_list_concat(_,_,_)).
  595safe_primitive(system:downcase_atom(_,_)).
  596safe_primitive(system:upcase_atom(_,_)).
  597safe_primitive(system:char_type(_,_)).
  598safe_primitive(system:normalize_space(_,_)).
  599safe_primitive(system:sub_atom_icasechk(_,_,_)).
  600                                        % numbers
  601safe_primitive(number_codes(_,_)).
  602safe_primitive(number_chars(_,_)).
  603safe_primitive(system:atom_number(_,_)).
  604safe_primitive(system:code_type(_,_)).
  605                                        % strings
  606safe_primitive(system:atom_string(_,_)).
  607safe_primitive(system:number_string(_,_)).
  608safe_primitive(system:string_chars(_, _)).
  609safe_primitive(system:string_codes(_, _)).
  610safe_primitive(system:string_code(_,_,_)).
  611safe_primitive(system:sub_string(_,_,_,_,_)).
  612safe_primitive(system:split_string(_,_,_,_)).
  613safe_primitive(system:atomics_to_string(_,_,_)).
  614safe_primitive(system:atomics_to_string(_,_)).
  615safe_primitive(system:string_concat(_,_,_)).
  616safe_primitive(system:string_length(_,_)).
  617safe_primitive(system:string_lower(_,_)).
  618safe_primitive(system:string_upper(_,_)).
  619safe_primitive(system:term_string(_,_)).
  620safe_primitive('$syspreds':term_string(_,_,_)).
  621                                        % Lists
  622safe_primitive(length(_,_)).
  623                                        % exceptions
  624safe_primitive(throw(_)).
  625safe_primitive(system:abort).
  626                                        % misc
  627safe_primitive(current_prolog_flag(_,_)).
  628safe_primitive(current_op(_,_,_)).
  629safe_primitive(system:sleep(_)).
  630safe_primitive(system:thread_self(_)).
  631safe_primitive(system:get_time(_)).
  632safe_primitive(system:statistics(_,_)).
  633safe_primitive(system:thread_statistics(Id,_,_)) :-
  634    (   var(Id)
  635    ->  instantiation_error(Id)
  636    ;   thread_self(Id)
  637    ).
  638safe_primitive(system:thread_property(Id,_)) :-
  639    (   var(Id)
  640    ->  instantiation_error(Id)
  641    ;   thread_self(Id)
  642    ).
  643safe_primitive(system:format_time(_,_,_)).
  644safe_primitive(system:format_time(_,_,_,_)).
  645safe_primitive(system:date_time_stamp(_,_)).
  646safe_primitive(system:stamp_date_time(_,_,_)).
  647safe_primitive(system:strip_module(_,_,_)).
  648safe_primitive('$messages':message_to_string(_,_)).
  649safe_primitive(system:import_module(_,_)).
  650safe_primitive(system:file_base_name(_,_)).
  651safe_primitive(system:file_directory_name(_,_)).
  652safe_primitive(system:file_name_extension(_,_,_)).
  653
  654safe_primitive(clause(H,_)) :- safe_clause(H).
  655safe_primitive(asserta(X)) :- safe_assert(X).
  656safe_primitive(assertz(X)) :- safe_assert(X).
  657safe_primitive(retract(X)) :- safe_assert(X).
  658safe_primitive(retractall(X)) :- safe_assert(X).
  659
  660% We need to do data flow analysis to find the tag of the
  661% target key before we can conclude that functions on dicts
  662% are safe.
  663safe_primitive('$dicts':'.'(_,K,_)) :- atom(K).
  664safe_primitive('$dicts':'.'(_,K,_)) :-
  665    (   nonvar(K)
  666    ->  dict_built_in(K)
  667    ;   instantiation_error(K)
  668    ).
  669
  670dict_built_in(get(_)).
  671dict_built_in(put(_)).
  672dict_built_in(put(_,_)).
  673
  674% The non-ISO system predicates.  These can be redefined, so we must
  675% be careful to ensure the system ones are used.
  676
  677safe_primitive(system:false).
  678safe_primitive(system:cyclic_term(_)).
  679safe_primitive(system:msort(_,_)).
  680safe_primitive(system:sort(_,_,_,_)).
  681safe_primitive(system:between(_,_,_)).
  682safe_primitive(system:succ(_,_)).
  683safe_primitive(system:plus(_,_,_)).
  684safe_primitive(system:term_variables(_,_)).
  685safe_primitive(system:term_variables(_,_,_)).
  686safe_primitive(system:'$term_size'(_,_,_)).
  687safe_primitive(system:atom_to_term(_,_,_)).
  688safe_primitive(system:term_to_atom(_,_)).
  689safe_primitive(system:atomic_list_concat(_,_,_)).
  690safe_primitive(system:atomic_list_concat(_,_)).
  691safe_primitive(system:downcase_atom(_,_)).
  692safe_primitive(system:upcase_atom(_,_)).
  693safe_primitive(system:is_list(_)).
  694safe_primitive(system:memberchk(_,_)).
  695safe_primitive(system:'$skip_list'(_,_,_)).
  696                                        % attributes
  697safe_primitive(system:get_attr(_,_,_)).
  698safe_primitive(system:get_attrs(_,_)).
  699safe_primitive(system:term_attvars(_,_)).
  700safe_primitive(system:del_attr(_,_)).
  701safe_primitive(system:del_attrs(_)).
  702safe_primitive('$attvar':copy_term(_,_,_)).
  703                                        % globals
  704safe_primitive(system:b_getval(_,_)).
  705safe_primitive(system:b_setval(Var,_)) :-
  706    safe_global_var(Var).
  707safe_primitive(system:nb_getval(_,_)).
  708safe_primitive('$syspreds':nb_setval(Var,_)) :-
  709    safe_global_var(Var).
  710safe_primitive(system:nb_linkval(Var,_)) :-
  711    safe_global_var(Var).
  712safe_primitive(system:nb_current(_,_)).
  713                                        % database
  714safe_primitive(system:assert(X)) :-
  715    safe_assert(X).
  716                                        % Output
  717safe_primitive(system:writeln(_)).
  718safe_primitive('$messages':print_message(_,_)).
  719
  720                                        % Stack limits (down)
  721safe_primitive('$syspreds':set_prolog_stack(Stack, limit(ByteExpr))) :-
  722    nonvar(Stack),
  723    stack_name(Stack),
  724    catch(Bytes is ByteExpr, _, fail),
  725    prolog_stack_property(Stack, limit(Current)),
  726    Bytes =< Current.
  727
  728stack_name(global).
  729stack_name(local).
  730stack_name(trail).
  731
  732safe_primitive('$tabling':abolish_all_tables).
  733safe_primitive('$tabling':'$wrap_tabled'(Module:_Head, _Mode)) :-
  734    prolog_load_context(module, Module),
  735    !.
  736safe_primitive('$tabling':'$moded_wrap_tabled'(Module:_Head,_,_,_)) :-
  737    prolog_load_context(module, Module),
  738    !.
  739
  740
  741% use_module/1.  We only allow for .pl files that are loaded from
  742% relative paths that do not contain /../
  743
  744safe_primitive(system:use_module(Spec, _Import)) :-
  745    safe_primitive(system:use_module(Spec)).
  746safe_primitive(system:use_module(Spec)) :-
  747    ground(Spec),
  748    (   atom(Spec)
  749    ->  Path = Spec
  750    ;   Spec =.. [_Alias, Segments],
  751        phrase(segments_to_path(Segments), List),
  752        atomic_list_concat(List, Path)
  753    ),
  754    \+ is_absolute_file_name(Path),
  755    \+ sub_atom(Path, _, _, _, '/../'),
  756    absolute_file_name(Spec, AbsFile,
  757                       [ access(read),
  758                         file_type(prolog),
  759                         file_errors(fail)
  760                       ]),
  761    file_name_extension(_, Ext, AbsFile),
  762    save_extension(Ext).
  763
  764% support predicates for safe_primitive, validating the safety of
  765% arguments to certain goals.
  766
  767segments_to_path(A/B) -->
  768    !,
  769    segments_to_path(A),
  770    [/],
  771    segments_to_path(B).
  772segments_to_path(X) -->
  773    [X].
  774
  775save_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.
  784safe_assert(C) :- cyclic_term(C), !, fail.
  785safe_assert(X) :- var(X), !, fail.
  786safe_assert(_Head:-_Body) :- !, fail.
  787safe_assert(_:_) :- !, fail.
  788safe_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.
  796safe_clause(H) :- var(H), !.
  797safe_clause(_:_) :- !, fail.
  798safe_clause(_).
 safe_global_var(+Name) is semidet
True if Name is a global variable to which assertion is considered safe.
  806safe_global_var(Name) :-
  807    var(Name),
  808    !,
  809    instantiation_error(Name).
  810safe_global_var(Name) :-
  811    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.
  823safe_meta(system:put_attr(V,M,A), Called) :-
  824    !,
  825    (   atom(M)
  826    ->  attr_hook_predicates([ attr_unify_hook(A, _),
  827                               attribute_goals(V,_,_),
  828                               project_attributes(_,_)
  829                             ], M, Called)
  830    ;   instantiation_error(M)
  831    ).
  832safe_meta(system:with_output_to(Output, G), [G]) :-
  833    safe_output(Output),
  834    !.
  835safe_meta(system:format(Format, Args), Calls) :-
  836    format_calls(Format, Args, Calls).
  837safe_meta(system:format(Output, Format, Args), Calls) :-
  838    safe_output(Output),
  839    format_calls(Format, Args, Calls).
  840safe_meta(prolog_debug:debug(_Term, Format, Args), Calls) :-
  841    format_calls(Format, Args, Calls).
  842safe_meta('$attvar':freeze(_Var,Goal), [Goal]).
  843safe_meta(phrase(NT,Xs0,Xs), [Goal]) :- % phrase/2,3 and call_dcg/2,3
  844    expand_nt(NT,Xs0,Xs,Goal).
  845safe_meta(phrase(NT,Xs0), [Goal]) :-
  846    expand_nt(NT,Xs0,[],Goal).
  847safe_meta('$dcg':call_dcg(NT,Xs0,Xs), [Goal]) :-
  848    expand_nt(NT,Xs0,Xs,Goal).
  849safe_meta('$dcg':call_dcg(NT,Xs0), [Goal]) :-
  850    expand_nt(NT,Xs0,[],Goal).
  851safe_meta('$tabling':abolish_table_subgoals(V), []) :-
  852    \+ qualified(V).
  853safe_meta('$tabling':current_table(V, _), []) :-
  854    \+ qualified(V).
  855safe_meta('$tabling':tnot(G), [G]).
  856
  857qualified(V) :-
  858    nonvar(V),
  859    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.
  869attr_hook_predicates([], _, []).
  870attr_hook_predicates([H|T], M, Called) :-
  871    (   predicate_property(M:H, defined)
  872    ->  Called = [M:H|Rest]
  873    ;   Called = Rest
  874    ),
  875    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.
  883expand_nt(NT, _Xs0, _Xs, _NewGoal) :-
  884    strip_module(NT, _, Plain),
  885    var(Plain),
  886    !,
  887    instantiation_error(Plain).
  888expand_nt(NT, Xs0, Xs, NewGoal) :-
  889    dcg_translate_rule((pseudo_nt --> NT),
  890                       (pseudo_nt(Xs0c,Xsc) :- NewGoal0)),
  891    (   var(Xsc), Xsc \== Xs0c
  892    ->  Xs = Xsc, NewGoal1 = NewGoal0
  893    ;   NewGoal1 = (NewGoal0, Xsc = Xs)
  894    ),
  895    (   var(Xs0c)
  896    ->  Xs0 = Xs0c,
  897        NewGoal = NewGoal1
  898    ;   NewGoal = ( Xs0 = Xs0c, NewGoal1 )
  899    ).
 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.
  906safe_meta_call(Goal, _, _Called) :-
  907    debug(sandbox(meta), 'Safe meta ~p?', [Goal]),
  908    fail.
  909safe_meta_call(Goal, Context, Called) :-
  910    (   safe_meta(Goal, Called)
  911    ->  true
  912    ;   safe_meta(Goal, Context, Called)
  913    ),
  914    !.     % call hook
  915safe_meta_call(Goal, _, Called) :-
  916    Goal = M:Plain,
  917    compound(Plain),
  918    compound_name_arity(Plain, Name, Arity),
  919    safe_meta_predicate(M:Name/Arity),
  920    predicate_property(Goal, meta_predicate(Spec)),
  921    !,
  922    called(Spec, Plain, Called).
  923safe_meta_call(M:Goal, _, Called) :-
  924    !,
  925    generic_goal(Goal, Gen),
  926    safe_meta(M:Gen),
  927    called(Gen, Goal, Called).
  928safe_meta_call(Goal, _, Called) :-
  929    generic_goal(Goal, Gen),
  930    safe_meta(Gen),
  931    called(Gen, Goal, Called).
  932
  933called(Gen, Goal, Called) :-
  934    compound_name_arity(Goal, _, Arity),
  935    called(1, Arity, Gen, Goal, Called).
  936
  937called(I, Arity, Gen, Goal, Called) :-
  938    I =< Arity,
  939    !,
  940    arg(I, Gen, Spec),
  941    (   calling_meta_spec(Spec)
  942    ->  arg(I, Goal, Called0),
  943        extend(Spec, Called0, G),
  944        Called = [G|Rest]
  945    ;   Called = Rest
  946    ),
  947    I2 is I+1,
  948    called(I2, Arity, Gen, Goal, Rest).
  949called(_, _, _, _, []).
  950
  951generic_goal(G, Gen) :-
  952    functor(G, Name, Arity),
  953    functor(Gen, Name, Arity).
  954
  955calling_meta_spec(V) :- var(V), !, fail.
  956calling_meta_spec(I) :- integer(I), !.
  957calling_meta_spec(^).
  958calling_meta_spec(//).
  959
  960
  961extend(^, G, Plain) :-
  962    !,
  963    strip_existential(G, Plain).
  964extend(//, DCG, Goal) :-
  965    !,
  966    (   expand_phrase(call_dcg(DCG,_,_), Goal)
  967    ->  true
  968    ;   instantiation_error(DCG)    % Ask more instantiation.
  969    ).                              % might not help, but does not harm.
  970extend(0, G, G) :- !.
  971extend(I, M:G0, M:G) :-
  972    !,
  973    G0 =.. List,
  974    length(Extra, I),
  975    append(List, Extra, All),
  976    G =.. All.
  977extend(I, G0, G) :-
  978    G0 =.. List,
  979    length(Extra, I),
  980    append(List, Extra, All),
  981    G =.. All.
  982
  983strip_existential(Var, Var) :-
  984    var(Var),
  985    !.
  986strip_existential(M:G0, M:G) :-
  987    !,
  988    strip_existential(G0, G).
  989strip_existential(_^G0, G) :-
  990    !,
  991    strip_existential(G0, G).
  992strip_existential(G, G).
 safe_meta(?Template)
  996safe_meta((0,0)).
  997safe_meta((0;0)).
  998safe_meta((0->0)).
  999safe_meta(system:(0*->0)).
 1000safe_meta(catch(0,*,0)).
 1001safe_meta(findall(*,0,*)).
 1002safe_meta('$bags':findall(*,0,*,*)).
 1003safe_meta(setof(*,^,*)).
 1004safe_meta(bagof(*,^,*)).
 1005safe_meta('$bags':findnsols(*,*,0,*)).
 1006safe_meta('$bags':findnsols(*,*,0,*,*)).
 1007safe_meta(system:call_cleanup(0,0)).
 1008safe_meta(system:setup_call_cleanup(0,0,0)).
 1009safe_meta(system:setup_call_catcher_cleanup(0,0,*,0)).
 1010safe_meta('$attvar':call_residue_vars(0,*)).
 1011safe_meta('$syspreds':call_with_inference_limit(0,*,*)).
 1012safe_meta('$syspreds':call_with_depth_limit(0,*,*)).
 1013safe_meta(^(*,0)).
 1014safe_meta(\+(0)).
 1015safe_meta(call(0)).
 1016safe_meta(call(1,*)).
 1017safe_meta(call(2,*,*)).
 1018safe_meta(call(3,*,*,*)).
 1019safe_meta(call(4,*,*,*,*)).
 1020safe_meta(call(5,*,*,*,*,*)).
 1021safe_meta(call(6,*,*,*,*,*,*)).
 1022safe_meta('$tabling':start_tabling(*,0)).
 1023safe_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.
 1030safe_output(Output) :-
 1031    var(Output),
 1032    !,
 1033    instantiation_error(Output).
 1034safe_output(atom(_)).
 1035safe_output(string(_)).
 1036safe_output(codes(_)).
 1037safe_output(codes(_,_)).
 1038safe_output(chars(_)).
 1039safe_output(chars(_,_)).
 1040safe_output(current_output).
 1041safe_output(current_error).
 format_calls(+Format, +FormatArgs, -Calls)
Find ~@ calls from Format and Args.
 1047:- public format_calls/3.                       % used in pengines_io
 1048
 1049format_calls(Format, _Args, _Calls) :-
 1050    var(Format),
 1051    !,
 1052    instantiation_error(Format).
 1053format_calls(Format, Args, Calls) :-
 1054    format_types(Format, Types),
 1055    (   format_callables(Types, Args, Calls)
 1056    ->  true
 1057    ;   throw(error(format_error(Format, Types, Args), _))
 1058    ).
 1059
 1060format_callables([], [], []).
 1061format_callables([callable|TT], [G|TA], [G|TG]) :-
 1062    !,
 1063    format_callables(TT, TA, TG).
 1064format_callables([_|TT], [_|TA], TG) :-
 1065    !,
 1066    format_callables(TT, TA, TG).
 1067
 1068
 1069                 /*******************************
 1070                 *    SAFE COMPILATION HOOKS    *
 1071                 *******************************/
 1072
 1073:- multifile
 1074    prolog:sandbox_allowed_directive/1,
 1075    prolog:sandbox_allowed_goal/1,
 1076    prolog:sandbox_allowed_expansion/1.
 prolog:sandbox_allowed_directive(:G) is det
Throws an exception if G is not considered a safe directive.
 1082prolog:sandbox_allowed_directive(Directive) :-
 1083    debug(sandbox(directive), 'Directive: ~p', [Directive]),
 1084    fail.
 1085prolog:sandbox_allowed_directive(Directive) :-
 1086    safe_directive(Directive),
 1087    !.
 1088prolog:sandbox_allowed_directive(M:PredAttr) :-
 1089    \+ prolog_load_context(module, M),
 1090    !,
 1091    debug(sandbox(directive), 'Cross-module directive', []),
 1092    permission_error(execute, sandboxed_directive, (:- M:PredAttr)).
 1093prolog:sandbox_allowed_directive(M:PredAttr) :-
 1094    safe_pattr(PredAttr),
 1095    !,
 1096    PredAttr =.. [Attr, Preds],
 1097    (   safe_pattr(Preds, Attr)
 1098    ->  true
 1099    ;   permission_error(execute, sandboxed_directive, (:- M:PredAttr))
 1100    ).
 1101prolog:sandbox_allowed_directive(_:Directive) :-
 1102    safe_source_directive(Directive),
 1103    !.
 1104prolog:sandbox_allowed_directive(_:Directive) :-
 1105    directive_loads_file(Directive, File),
 1106    !,
 1107    safe_path(File).
 1108prolog:sandbox_allowed_directive(G) :-
 1109    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),
    ...
 1127safe_pattr(dynamic(_)).
 1128safe_pattr(thread_local(_)).
 1129safe_pattr(volatile(_)).
 1130safe_pattr(discontiguous(_)).
 1131safe_pattr(multifile(_)).
 1132safe_pattr(public(_)).
 1133safe_pattr(meta_predicate(_)).
 1134safe_pattr(table(_)).
 1135
 1136safe_pattr(Var, _) :-
 1137    var(Var),
 1138    !,
 1139    instantiation_error(Var).
 1140safe_pattr((A,B), Attr) :-
 1141    !,
 1142    safe_pattr(A, Attr),
 1143    safe_pattr(B, Attr).
 1144safe_pattr(M:G, Attr) :-
 1145    !,
 1146    (   atom(M),
 1147        prolog_load_context(module, M)
 1148    ->  true
 1149    ;   Goal =.. [Attr,M:G],
 1150        permission_error(directive, sandboxed, (:- Goal))
 1151    ).
 1152safe_pattr(_, _).
 1153
 1154safe_source_directive(op(_,_,Name)) :-
 1155    !,
 1156    (   atom(Name)
 1157    ->  true
 1158    ;   is_list(Name),
 1159        maplist(atom, Name)
 1160    ).
 1161safe_source_directive(set_prolog_flag(Flag, Value)) :-
 1162    !,
 1163    atom(Flag), ground(Value),
 1164    safe_directive_flag(Flag, Value).
 1165safe_source_directive(style_check(_)).
 1166safe_source_directive(initialization(_)).   % Checked at runtime
 1167safe_source_directive(initialization(_,_)). % Checked at runtime
 1168
 1169directive_loads_file(use_module(library(X)), X).
 1170directive_loads_file(use_module(library(X), _Imports), X).
 1171directive_loads_file(ensure_loaded(library(X)), X).
 1172directive_loads_file(include(X), X).
 1173
 1174safe_path(X) :-
 1175    var(X),
 1176    !,
 1177    instantiation_error(X).
 1178safe_path(X) :-
 1179    (   atom(X)
 1180    ;   string(X)
 1181    ),
 1182    !,
 1183    \+ sub_atom(X, 0, _, 0, '..'),
 1184    \+ sub_atom(X, 0, _, _, '/'),
 1185    \+ sub_atom(X, 0, _, _, '../'),
 1186    \+ sub_atom(X, _, _, 0, '/..'),
 1187    \+ sub_atom(X, _, _, _, '/../').
 1188safe_path(A/B) :-
 1189    !,
 1190    safe_path(A),
 1191    safe_path(B).
 safe_directive_flag(+Flag, +Value) is det
True if it is safe to set the flag Flag in a directive 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.
 1203safe_directive_flag(generate_debug_info, _).
 1204safe_directive_flag(var_prefix, _).
 1205safe_directive_flag(double_quotes, _).
 1206safe_directive_flag(back_quotes, _).
 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.

 1221prolog:sandbox_allowed_expansion(Directive) :-
 1222    prolog_load_context(module, M),
 1223    debug(sandbox(expansion), 'Expand in ~p: ~p', [M, Directive]),
 1224    fail.
 1225prolog:sandbox_allowed_expansion(M:G) :-
 1226    prolog_load_context(module, M),
 1227    !,
 1228    safe_goal(M:G).
 1229prolog:sandbox_allowed_expansion(_,_).
 prolog:sandbox_allowed_goal(:G) is det
Throw an exception if it is not safe to call G
 1235prolog:sandbox_allowed_goal(G) :-
 1236    safe_goal(G).
 1237
 1238
 1239                 /*******************************
 1240                 *            MESSAGES          *
 1241                 *******************************/
 1242
 1243:- multifile
 1244    prolog:message//1,
 1245    prolog:message_context//1,
 1246    prolog:error_message//1. 1247
 1248prolog:message(error(instantiation_error, Context)) -->
 1249    { nonvar(Context),
 1250      Context = sandbox(_Goal,Parents),
 1251      numbervars(Context, 1, _)
 1252    },
 1253    [ 'Sandbox restriction!'-[], nl,
 1254      'Could not derive which predicate may be called from'-[]
 1255    ],
 1256    (   { Parents == [] }
 1257    ->  [ 'Search space too large'-[] ]
 1258    ;   callers(Parents, 10)
 1259    ).
 1260
 1261prolog:message_context(sandbox(_G, [])) --> !.
 1262prolog:message_context(sandbox(_G, Parents)) -->
 1263    [ nl, 'Reachable from:'-[] ],
 1264    callers(Parents, 10).
 1265
 1266callers([], _) --> !.
 1267callers(_,  0) --> !.
 1268callers([G|Parents], Level) -->
 1269    { NextLevel is Level-1
 1270    },
 1271    [ nl, '\t  ~p'-[G] ],
 1272    callers(Parents, NextLevel).
 1273
 1274prolog:message(bad_safe_declaration(Goal, File, Line)) -->
 1275    [ '~w:~d: Invalid safe_primitive/1 declaration: ~p'-
 1276      [File, Line, Goal] ].
 1277
 1278prolog:error_message(format_error(Format, Types, Args)) -->
 1279    format_error(Format, Types, Args).
 1280
 1281format_error(Format, Types, Args) -->
 1282    { length(Types, TypeLen),
 1283      length(Args, ArgsLen),
 1284      (   TypeLen > ArgsLen
 1285      ->  Problem = 'not enough'
 1286      ;   Problem = 'too many'
 1287      )
 1288    },
 1289    [ 'format(~q): ~w arguments (found ~w, need ~w)'-
 1290      [Format, Problem, ArgsLen, TypeLen]
 1291    ]