/
khepri_fun.erl
1360 lines (1245 loc) · 49.4 KB
/
khepri_fun.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%% This Source Code Form is subject to the terms of the Mozilla Public
%% License, v. 2.0. If a copy of the MPL was not distributed with this
%% file, You can obtain one at https://mozilla.org/MPL/2.0/.
%%
%% Copyright (c) 2021-2022 VMware, Inc. or its affiliates. All rights reserved.
%%
%% @doc Anonymous function extraction API.
%%
%% This module is responsible for extracting the code of an anonymous function.
%% The goal is to be able to store the extracted function and execute it later,
%% regardless of the availability of the initial Erlang module which declared
%% it.
%%
%% This module also provides a way for the caller to indicate forbidden
%% operations or function calls.
%%
%% This module works on assembly code to perform all checks and prepare the
%% storable copy of a function. It uses {@link beam_disasm:file/1} from the
%% `compiler' application to extract the assembly code. After the assembly
%% code was extracted and modified, the compiler is used again to compile the
%% code back to an executable module.
%%
%% If the anonymous function calls other functions, either in the same module
%% or in another one, the code of the called functions is extracted and copied
%% as well. This is to make sure the result is completely standalone.
%%
%% To avoid any copies of standard Erlang APIs or Khepri itself, it is
%% possible to specify a list of modules which should not be copied. In this
%% case, calls to functions in those modules are left unmodified.
%%
%% Once the code was extracted and verified, a new module is generated as an
%% "assembly form", ready to be compiled again to an executable module. The
%% generated module has a single `run/N' function. This function contains the
%% code of the extracted anonymous function.
%%
%% Because this process works on the assembly code, it means that if the
%% initial module hosting the anonymous function was compiled with Erlang
%% version N, it will probably not compile or run on older versions of Erlang.
%% The reason is that a newer compiler may use instructions which are unknown
%% to older runtimes.
%%
%% There is a special treatment for anonymous functions evaluated by
%% `erl_eval' (e.g. in the Erlang shell). "erl_eval functions" are lambdas
%% parsed from text and are evaluated using `erl_eval'.
%%
%% This kind of lambdas becomes a local function in the `erl_eval' module.
%%
%% Their assembly code isn't available in the `erl_eval' module. However, the
%% abstract code (i.e. after parsing but before compilation) is available in
%% the `env'. We compile that abstract code and extract the assembly from that
%% compiled beam.
-module(khepri_fun).
-include_lib("kernel/include/logger.hrl").
-include_lib("stdlib/include/assert.hrl").
-include("src/internal.hrl").
-export([to_standalone_fun/2,
exec/2]).
%% FIXME: compile:forms/2 is incorrectly specified and doesn't accept
%% assembly. This breaks compile/1 and causes a cascade of errors.
%%
%% The following basically disable Dialyzer for this module unfortunately...
%% This can be removed once we start using Erlang 25 to run Dialyzer.
-dialyzer({nowarn_function, [compile/1,
to_standalone_fun/2,
to_standalone_fun1/2,
to_standalone_fun2/2,
to_standalone_env/1,
to_standalone_arg/2,
handle_compilation_error/2,
add_comment_and_retry/4,
add_comment_to_function/7,
add_comment_to_code/5,
are_comments_conflicting/2]}).
-type fun_info() :: #{arity => arity(),
env => any(),
index => any(),
name => atom(),
module => module(),
new_index => any(),
new_uniq => any(),
pid => any(),
type => local | external,
uniq => any()}.
-type beam_instr() :: atom() | tuple().
-type label() :: pos_integer().
%% -------------------------------------------------------------------
%% Taken from lib/compiler/src/beam_disasm.hrl,
%% commit 7b3ffa5bb72a2ba84b07fb8a98d755216e78fa79
-record(function, {name :: atom(),
arity :: byte(),
entry :: beam_lib:label(), %% unnecessary ?
code = [] :: [beam_instr()]}).
-record(beam_file, {module :: module(),
labeled_exports = [] :: [beam_lib:labeled_entry()],
attributes = [] :: [beam_lib:attrib_entry()],
compile_info = [] :: [beam_lib:compinfo_entry()],
code = [] :: [#function{}]}).
%% -------------------------------------------------------------------
-type ensure_instruction_is_permitted_fun() ::
fun((beam_instr()) -> ok).
-type should_process_function_fun() ::
fun((module(), atom(), arity(), module()) -> boolean()).
-type is_standalone_fun_still_needed_fun() ::
fun((#{calls := #{mfa() => true},
errors := [any()]}) -> boolean()).
-type standalone_fun() :: #standalone_fun{} | fun().
-type options() :: #{ensure_instruction_is_permitted =>
ensure_instruction_is_permitted_fun(),
should_process_function =>
should_process_function_fun(),
is_standalone_fun_still_needed =>
is_standalone_fun_still_needed_fun()}.
-export_type([standalone_fun/0,
options/0]).
-record(state, {generated_module_name :: module() | undefined,
entrypoint :: mfa() | undefined,
checksums = #{} :: #{module() => binary()},
fun_info :: fun_info(),
calls = #{} :: #{mfa() => true},
all_calls = #{} :: #{mfa() => true},
functions = #{} :: #{mfa() => #function{}},
mfa_in_progress :: mfa() | undefined,
function_in_progress :: atom() | undefined,
next_label = 1 :: label(),
label_map = #{} :: #{{module(), label()} => label()},
errors = [] :: [any()],
options = #{} :: options()}).
-type asm() :: {module(),
[{atom(), arity()}],
[],
[#function{}],
label()}.
-spec to_standalone_fun(Fun, Options) -> StandaloneFun when
Fun :: fun(),
Options :: options(),
StandaloneFun :: standalone_fun().
to_standalone_fun(Fun, Options) ->
{StandaloneFun, _State} = to_standalone_fun1(Fun, Options),
StandaloneFun.
-spec to_standalone_fun1(Fun, Options) -> {StandaloneFun, State} when
Fun :: fun(),
Options :: options(),
StandaloneFun :: standalone_fun(),
State :: #state{}.
to_standalone_fun1(Fun, Options) ->
Info = maps:from_list(erlang:fun_info(Fun)),
#{module := Module,
name := Name,
arity := Arity} = Info,
State0 = #state{fun_info = Info,
all_calls = #{{Module, Name, Arity} => true},
options = Options},
to_standalone_fun2(Fun, State0).
-spec to_standalone_fun2(Fun, State) -> {StandaloneFun, State} when
Fun :: fun(),
State :: #state{},
StandaloneFun :: standalone_fun().
to_standalone_fun2(
Fun,
#state{fun_info = #{module := Module,
name := Name,
arity := Arity,
type := Type}} = State) ->
%% Don't extract functions like "fun dict:new/0" which are not meant to be
%% copied.
{ShouldProcess,
State1} = case Type of
local ->
should_process_function(
Module, Name, Arity, Module, State);
external ->
_ = code:ensure_loaded(Module),
case erlang:function_exported(Module, Name, Arity) of
true ->
should_process_function(
Module, Name, Arity, undefined, State);
false ->
throw({call_to_unexported_function,
{Module, Name, Arity}})
end
end,
case ShouldProcess of
true ->
State2 = pass1(State1),
%% Fun environment to standalone term.
%%
%% For "regular" lambdas, variables declared outside of the
%% function body are put in this `env'. We need to process them in
%% case they reference other lambdas for instance. We keep the end
%% result to store it alongside the generated module, but not
%% inside the module to avoid an increase in the number of
%% identical modules with different environment.
%%
%% However for `erl_eval' functions created from lambdas, the env
%% contains the parsed source code of the function. We don't need
%% to interpret it.
%%
%% TODO: `to_standalone_env()' uses `to_standalone_fun1()' to
%% extract and compile lambdas passed as arguments. It means they
%% are fully compiled even though
%% `is_standalone_fun_still_needed()' returns false later. This is
%% a waste of resources and this function can probably be split
%% into two parts to allow the environment to be extracted before
%% and compiled after, once we are sure we need to create the
%% final standalone fun.
{Env, State3} = case Module =:= erl_eval andalso Type =:= local of
false -> to_standalone_env(State2);
true -> {[], State2}
end,
%% We offer one last chance to the caller to determine if a
%% standalone function is still useful for him.
%%
%% This callback is only used for the top-level lambda. In other
%% words, if the `env' contains other lambdas (i.e. anonymous
%% functions passed as argument to the top-level one), the
%% callback is not used. However, calls and errors from those
%% inner lambdas are accumulated and can be used by the callback.
case is_standalone_fun_still_needed(State3) of
true ->
process_errors(State3),
Asm = pass2(State3),
{GeneratedModuleName, Beam} = compile(Asm),
StandaloneFun = #standalone_fun{
module = GeneratedModuleName,
beam = Beam,
arity = Arity,
env = Env},
{StandaloneFun, State3};
false ->
{Fun, State3}
end;
false ->
process_errors(State1),
{Fun, State1}
end.
-spec compile(Asm) -> {Module, Beam} when
Asm :: asm(), %% FIXME: compile:forms/2 is incorrectly specified.
Module :: module(),
Beam :: binary().
compile(Asm) ->
CompilerOptions = [from_asm,
binary,
warnings_as_errors,
return_errors,
return_warnings,
deterministic],
case compile:forms(Asm, CompilerOptions) of
{ok, Module, Beam, []} -> {Module, Beam};
Error -> handle_compilation_error(Asm, Error)
end.
handle_compilation_error(
Asm,
{error,
[{_GeneratedModuleName,
[{_, beam_validator,
{FailingFun,
{{get_tuple_element, Src, _Element, _Dst},
_,
{bad_type,
{needed, {t_tuple, _Size, _, _Fields} = NeededType},
{actual, any}}}}}]}],
[]} = Error) ->
VarInfo = {var_info, Src, [{type, NeededType}]},
Comment = {'%', VarInfo},
add_comment_and_retry(Asm, Error, FailingFun, Comment);
handle_compilation_error(
Asm,
%% Same as above, but returned by Erlang 23's compiler instead of Erlang 24+.
{error,
[{_GeneratedModuleName,
[{beam_validator,
{FailingFun,
{{get_tuple_element, Src, _Element, _Dst},
_,
{bad_type,
{needed, {t_tuple, _Size, _, _Fields} = NeededType},
{actual, any}}}}}]}],
[]} = Error) ->
VarInfo = {var_info, Src, [{type, NeededType}]},
Comment = {'%', VarInfo},
add_comment_and_retry(Asm, Error, FailingFun, Comment);
handle_compilation_error(Asm, Error) ->
throw({compilation_failure, Error, Asm}).
add_comment_and_retry(
Asm, Error, {GeneratedModuleName, Name, Arity} = _FailingFun, Comment) ->
{GeneratedModuleName,
Exports,
Attributes,
Functions,
Labels} = Asm,
Functions1 = add_comment_to_function(
Asm, Error, Functions, Name, Arity, Comment, []),
Asm1 = {GeneratedModuleName,
Exports,
Attributes,
Functions1,
Labels},
compile(Asm1).
add_comment_to_function(
Asm, Error,
[#function{name = Name, arity = Arity, code = Code} = Function | Rest],
Name, Arity, Comment, Result) ->
Code1 = add_comment_to_code(Asm, Error, Code, Comment, []),
Function1 = Function#function{code = Code1},
lists:reverse(Result) ++ [Function1 | Rest];
add_comment_to_function(
Asm, Error,
[Function | Rest], Name, Arity, Comment, Result) ->
add_comment_to_function(
Asm, Error, Rest, Name, Arity, Comment, [Function | Result]).
add_comment_to_code(
Asm, Error,
[{label, _} = Instruction | Rest],
Comment, Result) ->
add_comment_to_code(Asm, Error, Rest, Comment, [Instruction | Result]);
add_comment_to_code(
Asm, Error,
[{func_info, _, _, _} = Instruction | Rest],
Comment, Result) ->
add_comment_to_code(Asm, Error, Rest, Comment, [Instruction | Result]);
add_comment_to_code(
Asm, Error,
[{'%', _} = Instruction | Rest],
Comment, Result) ->
case are_comments_conflicting(Instruction, Comment) of
false ->
add_comment_to_code(
Asm, Error, Rest, Comment, [Instruction | Result]);
true ->
throw(
{conflicting_assembly_annotations,
Instruction, Comment, Error, Asm})
end;
add_comment_to_code(
_Asm, _Error,
Rest,
Comment, Result) ->
lists:reverse(Result) ++ [Comment | Rest].
are_comments_conflicting(
{'%', {var_info, Register, _}},
{'%', {var_info, Register, _}}) ->
%% If we are about to generate two `var_info' comments affecting the same
%% register (i.e. same variable), we abort.
true;
are_comments_conflicting(_Comment1, _Comment2) ->
false.
-spec exec(StandaloneFun, Args) -> Ret when
StandaloneFun :: standalone_fun(),
Args :: [any()],
Ret :: any().
exec(
#standalone_fun{module = Module,
beam = Beam,
arity = Arity,
env = Env},
Args) when length(Args) =:= Arity ->
case code:is_loaded(Module) of
false ->
{module, _} = code:load_binary(Module, ?MODULE_STRING, Beam),
ok;
_ ->
ok
end,
Env1 = to_actual_arg(Env),
erlang:apply(Module, run, Args ++ Env1);
exec(#standalone_fun{} = StandaloneFun, Args) ->
exit({badarity, {StandaloneFun, Args}});
exec(Fun, Args) ->
erlang:apply(Fun, Args).
%% -------------------------------------------------------------------
%% Code processing [Pass 1]
%% -------------------------------------------------------------------
-spec pass1(State) -> State when
State :: #state{}.
pass1(
#state{fun_info = #{module := erl_eval, type := local} = Info,
checksums = Checksums} = State) ->
#{module := Module,
name := Name,
arity := Arity} = Info,
Checksum = maps:get(new_uniq, Info),
?assert(is_binary(Checksum)),
Checksums1 = Checksums#{Module => Checksum},
State1 = State#state{checksums = Checksums1,
entrypoint = {Module, Name, Arity}},
pass1_process_function(Module, Name, Arity, State1);
pass1(
#state{fun_info = Info,
checksums = Checksums} = State) ->
#{module := Module,
name := Name,
arity := Arity,
env := Env} = Info,
%% Internally, a lambda which takes arguments and values from its
%% environment (i.e. variables declared in the function which defined that
%% lambda).
InternalArity = Arity + length(Env),
State1 = case maps:get(type, Info) of
local ->
Checksum = maps:get(new_uniq, Info),
?assert(is_binary(Checksum)),
Checksums1 = Checksums#{Module => Checksum},
State#state{checksums = Checksums1};
external ->
State
end,
State2 = State1#state{entrypoint = {Module, Name, InternalArity}},
pass1_process_function(Module, Name, InternalArity, State2).
-spec pass1_process_function(Module, Name, Arity, State) -> State when
Module :: module(),
Name :: atom(),
Arity :: arity(),
State :: #state{}.
pass1_process_function(
Module, Name, Arity,
#state{functions = Functions} = State)
when is_map_key({Module, Name, Arity}, Functions) ->
State;
pass1_process_function(Module, Name, Arity, State) ->
MFA = {Module, Name, Arity},
State1 = State#state{mfa_in_progress = MFA,
calls = #{}},
{Function0, State2} = lookup_function(Module, Name, Arity, State1),
{Function1, State3} = pass1_process_function_code(Function0, State2),
#state{calls = Calls,
functions = Functions} = State3,
Functions1 = Functions#{MFA => Function1},
State4 = State3#state{functions = Functions1},
%% Recurse with called functions.
maps:fold(
fun({M, F, A}, true, St) ->
pass1_process_function(M, F, A, St)
end, State4, Calls).
-spec pass1_process_function_code(Function, State) -> {Function, State} when
Function :: #function{},
State :: #state{}.
pass1_process_function_code(
#function{entry = OldEntryLabel,
code = Instructions} = Function,
#state{mfa_in_progress = {Module, _, _} = MFA,
next_label = NextLabel,
functions = Functions} = State) ->
?assertNot(maps:is_key(MFA, Functions)),
%% Compute label diff.
{label, FirstLabel} = lists:keyfind(label, 1, Instructions),
LabelDiff = NextLabel - FirstLabel,
%% pass1_process_instructions
{Instructions1, State1} = pass1_process_instructions(Instructions, State),
%% Compute its new entry label.
#state{label_map = LabelMap} = State1,
LabelKey = {Module, OldEntryLabel},
NewEntryLabel = maps:get(LabelKey, LabelMap),
?assertEqual(LabelDiff, NewEntryLabel - OldEntryLabel),
%% Rename function & fix its entry label.
Function1 = Function#function{
entry = NewEntryLabel,
code = Instructions1},
{Function1, State1}.
-spec pass1_process_instructions(Instructions, State) ->
{Instructions, State} when
Instructions :: [beam_instr()],
State :: #state{}.
pass1_process_instructions(Instructions, State) ->
pass1_process_instructions(Instructions, State, []).
%% The first group of clauses of this function patch incorrectly decoded
%% instructions. These clauses recurse after fixing the instruction to enter
%% the second group of clauses who.
%%
%% The second group of clauses:
%% 1. ensures the instruction is known and allowed,
%% 2. records all calls that need their code to be copied and
%% 3. records jump labels.
%% First group.
pass1_process_instructions(
[{bs_append, _, _, _, _, _, _, {field_flags, FF}, _} = Instruction0 | Rest],
State,
Result)
when is_integer(FF) ->
%% `beam_disasm' did not decode this instruction's field flags.
Instruction = decode_field_flags(Instruction0, 8),
pass1_process_instructions([Instruction | Rest], State, Result);
pass1_process_instructions(
[{bs_init2, _, _, _, _, {field_flags, FF}, _} = Instruction0 | Rest],
State,
Result)
when is_integer(FF) ->
%% `beam_disasm' did not decode this instruction's field flags.
Instruction = decode_field_flags(Instruction0, 6),
pass1_process_instructions([Instruction | Rest], State, Result);
pass1_process_instructions(
[{BsPutSomething, _, _, _, {field_flags, FF}, _} = Instruction0 | Rest],
State,
Result)
when (BsPutSomething =:= bs_put_binary orelse
BsPutSomething =:= bs_put_integer) andalso
is_integer(FF) ->
%% `beam_disasm' did not decode this instruction's field flags.
Instruction = decode_field_flags(Instruction0, 5),
pass1_process_instructions([Instruction | Rest], State, Result);
pass1_process_instructions(
[{bs_start_match3, Fail, Bin, {u, Live}, Dst} | Rest],
State,
Result) ->
%% `beam_disasm' did not decode this instruction correctly. We need to
%% patch it to:
%% 1. add `test' as the first element in the tuple,
%% 2. swap `Bin' and `Live',
%% 3. put `Bin' in a list and
%% 4. store `Live' as an integer.
Instruction = {test, bs_start_match3, Fail, Live, [Bin], Dst},
pass1_process_instructions([Instruction | Rest], State, Result);
pass1_process_instructions(
[{bs_start_match4, Fail, {u, Live}, Src, Dst} | Rest],
State,
Result) ->
%% `beam_disasm' did not decode this instruction correctly. We need to
%% patch it to store `Live' as an integer.
Instruction = {bs_start_match4, Fail, Live, Src, Dst},
pass1_process_instructions([Instruction | Rest], State, Result);
pass1_process_instructions(
[{test, BsGetSomething,
Fail, [Ctx, Live, Size, Unit, {field_flags, FF} = FieldFlags0, Dst]}
| Rest],
State,
Result)
when (BsGetSomething =:= bs_get_integer2 orelse
BsGetSomething =:= bs_get_binary2) andalso
is_integer(FF) ->
%% `beam_disasm' did not decode this instruction correctly. We need to
%% patch it to move `Live' before the list. We also need to decode field
%% flags.
FieldFlags = decode_field_flags(FieldFlags0),
Instruction = {test, BsGetSomething,
Fail, Live, [Ctx, Size, Unit, FieldFlags], Dst},
pass1_process_instructions([Instruction | Rest], State, Result);
pass1_process_instructions(
[{BsGetSomething, Ctx, Dst, {u, Live}} | Rest],
State,
Result)
when BsGetSomething =:= bs_get_position orelse
BsGetSomething =:= bs_get_tail ->
%% `beam_disasm' did not decode this instruction correctly. We need to
%% patch it to store `Live' as an integer.
Instruction = {BsGetSomething, Ctx, Dst, Live},
pass1_process_instructions([Instruction | Rest], State, Result);
pass1_process_instructions(
[{test, bs_match_string, Fail, [Ctx, Stride, String]} | Rest],
State,
Result) when is_binary(String) ->
%% `beam_disasm' did not decode this instruction correctly. We need to
%% patch it to put `String' inside a tuple.
Instruction = {test, bs_match_string,
Fail, [Ctx, Stride, {string, String}]},
pass1_process_instructions([Instruction | Rest], State, Result);
pass1_process_instructions(
[{raise, Fail, Args, Dst} | Rest],
State,
Result) ->
%% `beam_disasm` did not decode this instruction correctly. `raise'
%% should be translated into a `bif'.
Instruction = {bif, raise, Fail, Args, Dst},
pass1_process_instructions([Instruction | Rest], State, Result);
%% Second group.
pass1_process_instructions(
[{Call, Arity, {Module, Name, Arity}} = Instruction | Rest],
State,
Result)
when Call =:= call orelse Call =:= call_only ->
State1 = ensure_instruction_is_permitted(Instruction, State),
State2 = pass1_process_call(Module, Name, Arity, State1),
pass1_process_instructions(Rest, State2, [Instruction | Result]);
pass1_process_instructions(
[{Call, Arity, {extfunc, Module, Name, Arity}} = Instruction | Rest],
State,
Result)
when Call =:= call_ext orelse Call =:= call_ext_only ->
State1 = ensure_instruction_is_permitted(Instruction, State),
State2 = pass1_process_call(Module, Name, Arity, State1),
pass1_process_instructions(Rest, State2, [Instruction | Result]);
pass1_process_instructions(
[{call_last, Arity, {Module, Name, Arity}, _} = Instruction
| Rest],
State,
Result) ->
State1 = ensure_instruction_is_permitted(Instruction, State),
State2 = pass1_process_call(Module, Name, Arity, State1),
pass1_process_instructions(Rest, State2, [Instruction | Result]);
pass1_process_instructions(
[{call_ext_last, Arity, {extfunc, Module, Name, Arity}, _} = Instruction
| Rest],
State,
Result) ->
State1 = ensure_instruction_is_permitted(Instruction, State),
State2 = pass1_process_call(Module, Name, Arity, State1),
pass1_process_instructions(Rest, State2, [Instruction | Result]);
pass1_process_instructions(
[{label, OldLabel} | Rest],
#state{mfa_in_progress = {Module, _, _},
next_label = NewLabel,
label_map = LabelMap} = State,
Result) ->
Instruction = {label, NewLabel},
LabelKey = {Module, OldLabel},
?assertNot(maps:is_key(LabelKey, LabelMap)),
LabelMap1 = LabelMap#{LabelKey => NewLabel},
State1 = State#state{next_label = NewLabel + 1,
label_map = LabelMap1},
pass1_process_instructions(Rest, State1, [Instruction | Result]);
pass1_process_instructions(
[{line, _} | Rest],
State,
Result) ->
%% Drop this instruction.
pass1_process_instructions(Rest, State, Result);
pass1_process_instructions(
[{make_fun2, {Module, Name, Arity}, _, _, _} = Instruction | Rest],
State,
Result) ->
State1 = ensure_instruction_is_permitted(Instruction, State),
State2 = pass1_process_call(Module, Name, Arity, State1),
pass1_process_instructions(Rest, State2, [Instruction | Result]);
pass1_process_instructions(
[{make_fun3, {Module, Name, Arity}, _, _, _, _} = Instruction | Rest],
State,
Result) ->
State1 = ensure_instruction_is_permitted(Instruction, State),
State2 = pass1_process_call(Module, Name, Arity, State1),
pass1_process_instructions(Rest, State2, [Instruction | Result]);
pass1_process_instructions(
[Instruction | Rest],
State,
Result) ->
State1 = ensure_instruction_is_permitted(Instruction, State),
pass1_process_instructions(Rest, State1, [Instruction | Result]);
pass1_process_instructions(
[],
State,
Result) ->
{lists:reverse(Result), State}.
-spec pass1_process_call(Module, Name, Arity, State) -> State when
Module :: module(),
Name :: atom(),
Arity :: arity(),
State :: #state{}.
pass1_process_call(
Module, Name, Arity,
#state{mfa_in_progress = {Module, Name, Arity}} = State) ->
State;
pass1_process_call(
Module, Name, Arity,
#state{mfa_in_progress = {FromModule, _, _},
functions = Functions,
calls = Calls,
all_calls = AllCalls} = State) ->
CallKey = {Module, Name, Arity},
AllCalls1 = AllCalls#{CallKey => true},
case should_process_function(Module, Name, Arity, FromModule, State) of
{true, State1} ->
case Functions of
#{CallKey := _} ->
State1;
_ ->
Calls1 = Calls#{CallKey => true},
State1#state{calls = Calls1,
all_calls = AllCalls1}
end;
{false, State1} ->
State1#state{all_calls = AllCalls1}
end.
-spec lookup_function(Module, Name, Arity, State) -> {Function, State} when
Module :: module(),
Name :: atom(),
Arity :: non_neg_integer() | undefined,
State :: #state{},
Function :: #function{}.
lookup_function(
erl_eval = Module, Name, _Arity,
#state{fun_info = #{module := Module,
name := Name,
arity := Arity,
env := Env}} = State) ->
%% There is a special case for `erl_eval' local functions: they are
%% lambdas dynamically parsed, compiled and loaded by `erl_eval' and
%% appear as local functions inside `erl_eval' directly.
%%
%% However `erl_eval' module doesn't contain the assembly for those
%% functions. Instead, the abstract form of the source code is available
%% in the lambda's env.
%%
%% There here, we compile the abstract form and extract the assembly from
%% the compiled beam. This allows to use the rest of `khepri_fun'
%% unmodified.
#beam_file{code = Code} = erl_eval_fun_to_asm(Module, Name, Arity, Env),
{lookup_function1(Code, Name, Arity), State};
lookup_function(Module, Name, Arity, State) ->
{#beam_file{code = Code}, State1} = disassemble_module(Module, State),
{lookup_function1(Code, Name, Arity), State1}.
lookup_function1(
[#function{name = Name, arity = Arity} = Function | _],
Name, Arity) when is_integer(Arity) ->
Function;
lookup_function1(
[#function{name = Name} = Function | _],
Name, undefined) ->
Function;
lookup_function1(
[_ | Rest],
Name, Arity) ->
lookup_function1(Rest, Name, Arity).
-spec erl_eval_fun_to_asm(Module, Name, Arity, Env) -> BeamFileRecord when
Module :: module(),
Name :: atom(),
Arity :: arity(),
Env :: any(),
BeamFileRecord :: #beam_file{}.
%% @private
erl_eval_fun_to_asm(Module, Name, Arity, [{Bindings, _, _, Clauses}])
when Bindings =:= [] orelse %% Erlang is using a list for bindings,
Bindings =:= #{} -> %% but Elixir is using a map.
%% We construct an abstract form based on the `env' of the lambda loaded
%% by `erl_eval'.
Anno = erl_anno:from_term(1),
Forms = [{attribute, Anno, module, Module},
{attribute, Anno, export, [{Name, Arity}]},
{function, Anno, Name, Arity, Clauses}],
%% The abstract form is now compiled to binary code. Then, the assembly
%% code is extracted from the compiled beam.
CompilerOptions = [from_abstr,
binary,
return_errors,
return_warnings,
deterministic],
case compile:forms(Forms, CompilerOptions) of
{ok, Module, Beam, _Warnings} ->
%% We can ignore warnings because the lambda was already parsed
%% and compiled before by `erl_eval' previously.
do_disassemble(Beam);
Error ->
throw({erl_eval_fun_compilation_failure, Error})
end.
-spec disassemble_module(Module, State) -> {BeamFileRecord, State} when
Module :: module(),
State :: #state{},
BeamFileRecord :: #beam_file{}.
-define(ASM_CACHE_KEY(Module, Checksum),
{?MODULE, asm_cache, Module, Checksum}).
disassemble_module(Module, #state{checksums = Checksums} = State) ->
case Checksums of
#{Module := Checksum} ->
{BeamFileRecord, Checksum} = disassemble_module1(
Module, Checksum),
{BeamFileRecord, State};
_ ->
{BeamFileRecord, Checksum} = disassemble_module1(
Module, undefined),
?assert(is_binary(Checksum)),
Checksums1 = Checksums#{Module => Checksum},
State1 = State#state{checksums = Checksums1},
{BeamFileRecord, State1}
end.
disassemble_module1(Module, Checksum) when is_binary(Checksum) ->
Key = ?ASM_CACHE_KEY(Module, Checksum),
case persistent_term:get(Key, undefined) of
#beam_file{} = BeamFileRecord ->
{BeamFileRecord, Checksum};
undefined ->
{Module, Beam, _} = get_object_code(Module),
{ok, {Module, ActualChecksum}} = beam_lib:md5(Beam),
case ActualChecksum of
Checksum ->
BeamFileRecord = do_disassemble_and_cache(
Module, Checksum, Beam),
{BeamFileRecord, Checksum};
_ ->
throw(
{mismatching_module_checksum,
Module, Checksum, ActualChecksum})
end
end;
disassemble_module1(Module, undefined) ->
{Module, Beam, _} = get_object_code(Module),
{ok, {Module, Checksum}} = beam_lib:md5(Beam),
BeamFileRecord = do_disassemble_and_cache(Module, Checksum, Beam),
{BeamFileRecord, Checksum}.
get_object_code(Module) ->
case code:get_object_code(Module) of
{Module, Beam, Filename} -> {Module, Beam, Filename};
error -> throw({module_not_found, Module})
end.
do_disassemble_and_cache(Module, Checksum, Beam) ->
Key = ?ASM_CACHE_KEY(Module, Checksum),
BeamFileRecord = do_disassemble(Beam),
persistent_term:put(Key, BeamFileRecord),
BeamFileRecord.
do_disassemble(Beam) ->
beam_disasm:file(Beam).
%% The field flags, which correspond to `Var/signed', `Var/unsigned',
%% `Var/little', `Var/big' and `Var/native' in the bitstring syntax, need to
%% be decoded here. It's the opposite to:
%% https://github.com/erlang/otp/blob/OTP-24.2/lib/compiler/src/beam_asm.erl#L486-L493
%%
%% The field flags bit field becomes a sublist of [signed, little, native].
decode_field_flags(Instruction, Pos) when is_tuple(Instruction) ->
FieldFlags0 = element(Pos, Instruction),
FieldFlags1 = decode_field_flags(FieldFlags0),
setelement(Pos, Instruction, FieldFlags1).
-spec decode_field_flags(FieldFlagsBitFieldsTuple | FieldFlagsBitField) ->
FieldFlagsTuple | FieldFlags when
FieldFlagsBitFieldsTuple :: {field_flags, FieldFlagsBitField},
FieldFlagsBitField :: non_neg_integer(),
FieldFlagsTuple :: {field_flags, FieldFlags},
FieldFlags :: [FieldFlag],
FieldFlag :: little | signed | native.
decode_field_flags(0) ->
[];
decode_field_flags(FieldFlags) when is_integer(FieldFlags) ->
lists:filtermap(
fun
(little) -> (FieldFlags band 16#02) == 16#02;
(signed) -> (FieldFlags band 16#04) == 16#04;
(native) -> (FieldFlags band 16#10) == 16#10
end, [signed, little, native]);
decode_field_flags({field_flags, FieldFlagsBitField}) ->
FieldFlags = decode_field_flags(FieldFlagsBitField),
{field_flags, FieldFlags}.
-spec ensure_instruction_is_permitted(Instruction, State) ->
State when
Instruction :: beam_instr(),
State :: #state{}.
ensure_instruction_is_permitted(
Instruction,
#state{options = #{ensure_instruction_is_permitted := Callback},
errors = Errors} = State)
when is_function(Callback) ->
try
Callback(Instruction),
State
catch
throw:Error ->
Errors1 = Errors ++ [Error],
State#state{errors = Errors1}
end;
ensure_instruction_is_permitted(_Instruction, State) ->
State.
-spec should_process_function(Module, Name, Arity, FromModule, State) ->
{ShouldProcess, State} when
Module :: module(),
Name :: atom(),
Arity :: arity(),
FromModule :: module(),
State :: #state{},
ShouldProcess :: boolean().
should_process_function(
erl_eval, Name, Arity, _FromModule,
#state{fun_info = #{module := erl_eval,
name := Name,
arity := Arity,
type := local}} = State) ->
%% We want to process lambas loaded by `erl_eval'
%% even though we wouldn't do that with the
%% regular `erl_eval' API.
{true, State};
should_process_function(
Module, Name, Arity, FromModule,
#state{options = #{should_process_function := Callback},
errors = Errors} = State)
when is_function(Callback) ->
try
ShouldProcess = Callback(Module, Name, Arity, FromModule),
{ShouldProcess, State}
catch
throw:Error ->
Errors1 = Errors ++ [Error],
State1 = State#state{errors = Errors1},
{false, State1}
end;
should_process_function(Module, Name, Arity, _FromModule, State) ->
{default_should_process_function(Module, Name, Arity),
State}.
default_should_process_function(erlang, _Name, _Arity) -> false;
default_should_process_function(_Module, _Name, _Arity) -> true.
-spec is_standalone_fun_still_needed(State) -> IsNeeded when
State :: #state{},
IsNeeded :: boolean().
is_standalone_fun_still_needed(
#state{options = #{is_standalone_fun_still_needed := Callback},
all_calls = Calls,
errors = Errors})
when is_function(Callback) ->
Callback(#{calls => Calls,
errors => Errors});
is_standalone_fun_still_needed(_State) ->
true.
-spec process_errors(State) -> ok | no_return() when
State :: #state{}.
%% TODO: Return all errors?
process_errors(#state{errors = []}) -> ok;
process_errors(#state{errors = [Error | _]}) -> throw(Error).
%% -------------------------------------------------------------------
%% Code processing [Pass 2]
%% -------------------------------------------------------------------
-spec pass2(State) -> Asm when
State :: #state{},
Asm :: asm().
pass2(
#state{functions = Functions,