-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
init.erl
1961 lines (1712 loc) · 59.7 KB
/
init.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
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1996-2024. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%
%% New initial version of init.
%% Booting from a script. The script is fetched either from
%% a local file or distributed from another erlang node.
%%
%% Flags:
%% -boot File : Absolute file name of the boot script.
%% -boot_var Var Value
%% : $Var in the boot script is expanded to
%% Value.
%% -loader LoaderMethod
%% : efile, inet
%% (Optional - default efile)
%% -hosts [Node] : List of hosts from which we can boot.
%% (Mandatory if -loader inet)
%% -mode interactive : Auto load modules not needed at startup (default system behaviour).
%% -mode embedded : Load all modules in the boot script, disable auto loading.
%% -path : Override path in bootfile.
%% -pa Path+ : Add my own paths first.
%% -pz Path+ : Add my own paths last.
%% -run : Start own processes.
%% -s : Start own processes.
%% -S : Start own processes and terminate further option processing.
%%
%% Experimental flags:
%% -profile_boot : Use an 'eprof light' to profile boot sequence
%% -init_debug : Activate debug printouts in init
%% -loader_debug : Activate debug printouts in erl_prim_loader
%% -code_path_choice : strict | relaxed
-module(init).
-moduledoc """
Coordination of system startup.
This module is preloaded and contains the code for the `init` system process
that coordinates the startup of the system. The first function evaluated at
startup is [`boot(BootArgs)`](`boot/1`), where `BootArgs` is a list of
command-line arguments supplied to the Erlang runtime system from the local
operating system; see [`erl(1)`](erl_cmd.md).
`init` reads the boot script, which contains instructions on how to initiate the
system. For more information about boot scripts, see
[`script(4)`](`e:sasl:script.md`).
`init` also contains functions to restart, reboot, and stop the system.
[](){: #flags }
## Command-Line Flags
> #### Warning {: .warning }
>
> The support for loading of code from archive files is experimental. The only
> purpose of releasing it before it is ready is to obtain early feedback. The
> file format, semantics, interfaces, and so on, can be changed in a future
> release.
The `init` module interprets the following command-line flags:
- **`--`** - Everything following `--` up to the next flag is considered plain
arguments and can be retrieved using `get_plain_arguments/0`.
- **`-code_path_choice Choice`** - Can be set to `strict` or `relaxed`. It
controls how each directory in the code path is to be interpreted:
- Strictly as it appears in the `boot script`, or
- `init` is to be more relaxed and try to find a suitable directory if it can
choose from a regular `ebin` directory and an `ebin` directory in an archive
file.
It defaults to `strict` from OTP 27 and this option is scheduled for removal
in OTP 28.
- **`-epmd_module Module`** - Specifies the module to use for registration and
lookup of node names. Defaults to `erl_epmd`.
- **`-eval Expr`** - Scans, parses, and evaluates an arbitrary expression `Expr`
during system initialization. If any of these steps fail (syntax error, parse
error, or exception during evaluation), Erlang stops with an error message. In
the following example Erlang is used as a hexadecimal calculator:
```text
% erl -noshell -eval 'R = 16#1F+16#A0, io:format("~.16B~n", [R])' \\
-s erlang halt
BF
```
If multiple `-eval` expressions are specified, they are evaluated sequentially
in the order specified. `-eval` expressions are evaluated sequentially with
`-s` and `-run` function calls (this also in the order specified). As with
`-s` and `-run`, an evaluation that does not terminate blocks the system
initialization process.
- **`-extra`** - Everything following `-extra` is considered plain arguments and
can be retrieved using `get_plain_arguments/0`.
Example:
```erlang
% erl -extra +A 1 --
...
1> init:get_plain_arguments().
["+A","1","--"]
```
The `-extra` flag can be passed on the command line, through `ERL_*FLAGS` or
`-args_file`. It only effects the remaining command-line flags in the entity
in which it is passed. If multiple `-extra` flags are passed they are
concatenated using the same order rules as `ERL_*FLAGS` or `-args_file` in
which they are given.
Example:
```text
% ERL_AFLAGS="-extra a" ERL_ZFLAGS="-extra d" erl -extra b -extra c
...
1> init:get_plain_arguments().
["a","b","-extra","c","d"]
```
- **`-S Mod [Func [Arg1, Arg2, ...]]`** - Evaluates the specified function call
during system initialization. `Func` defaults to `start`. If no arguments are
provided, the function is assumed to be of arity 0. Otherwise it is assumed to
be of arity 1, taking the list `[Arg1,Arg2,...]` as argument. All arguments
are passed as strings. If an exception is raised, Erlang stops with an error
message.
Example:
```text
% erl -S httpd serve --port 8080 /var/www/html
```
This starts the Erlang runtime system and evaluates the function
`httpd:serve(["--port", "8080", "/var/www/html"])`. All arguments up to the
end of the command line will be passed to the called function.
The function is executed sequentially in an initialization process, which then
terminates normally and passes control to the user. This means that a `-S`
call that does not return blocks further processing; to avoid this, use some
variant of `spawn` in such cases.
The `-S` flag is only allowed on the command line. If passed through
`ERL_*FLAGS` or `-args_file` it will be parsed as a normal command line flag.
- **`-run Mod [Func [Arg1, Arg2, ...]]`** - Evaluates the specified function
call during system initialization. `Func` defaults to `start`. If no arguments
are provided, the function is assumed to be of arity 0. Otherwise it is
assumed to be of arity 1, taking the list `[Arg1,Arg2,...]` as argument. All
arguments are passed as strings. If an exception is raised, Erlang stops with
an error message.
Example:
```text
% erl -run foo -run foo bar -run foo bar baz 1 2
```
This starts the Erlang runtime system and evaluates the following functions:
```text
foo:start()
foo:bar()
foo:bar(["baz", "1", "2"]).
```
The functions are executed sequentially in an initialization process, which
then terminates normally and passes control to the user. This means that a
`-run` call that does not return blocks further processing; to avoid this, use
some variant of `spawn` in such cases.
> #### Note {: .info }
>
> This flag will not forward arguments beginning with a hyphen (-) to the
> specified function, as these will be interpreted as flags to the runtime. If
> the function uses flags in this form, it is advised to use `-S` instead.
- **`-s Mod [Func [Arg1, Arg2, ...]]`** - Evaluates the specified function call
during system initialization. `Func` defaults to `start`. If no arguments are
provided, the function is assumed to be of arity 0. Otherwise it is assumed to
be of arity 1, taking the list `[Arg1,Arg2,...]` as argument. All arguments
are passed as atoms. If an exception is raised, Erlang stops with an error
message.
Example:
```text
% erl -s foo -s foo bar -s foo bar baz 1 2
```
This starts the Erlang runtime system and evaluates the following functions:
```text
foo:start()
foo:bar()
foo:bar([baz, '1', '2']).
```
The functions are executed sequentially in an initialization process, which
then terminates normally and passes control to the user. This means that a
`-s` call that does not return blocks further processing; to avoid this, use
some variant of `spawn` in such cases.
Because of the limited length of atoms, it is recommended to use `-run`
instead.
> #### Note {: .info }
>
> This flag will not forward arguments beginning with a hyphen (-) to the
> specified function, as these will be interpreted as flags to the runtime. If
> the function uses flags in this form, it is advised to use `-S` instead,
> with the additional caveat that arguments are passed as strings instead of
> atoms.
## Example
```erlang
% erl -- a b -children thomas claire -ages 7 3 -- x y
...
1> init:get_plain_arguments().
["a","b","x","y"]
2> init:get_argument(children).
{ok,[["thomas","claire"]]}
3> init:get_argument(ages).
{ok, [["7","3"]]}
4> init:get_argument(silly).
error
```
## See Also
`m:erl_prim_loader`, `m:heart`
""".
-export([restart/1,restart/0,reboot/0,stop/0,stop/1,
get_status/0,boot/1,get_arguments/0,get_plain_arguments/0,
get_argument/1,script_id/0,script_name/0]).
%% for the on_load functionality; not for general use
-export([run_on_load_handlers/0]).
%% internal exports
-export([fetch_loaded/0,ensure_loaded/1,make_permanent/2,
notify_when_started/1,wait_until_started/0,
objfile_extension/0, archive_extension/0,code_path_choice/0,
get_configfd/1, set_configfd/2]).
-include_lib("kernel/include/file.hrl").
-doc "Current status of init.".
-type internal_status() :: 'starting' | 'started' | 'stopping'.
-doc "Code loading mode.".
-type mode() :: 'embedded' | 'interactive'.
-record(state, {flags = [],
args = [],
start = [],
kernel = [] :: [{atom(), pid()}],
bootpid :: pid(),
status = {starting, starting} :: {internal_status(), term()},
script_id = [],
loaded = [],
subscribed = [],
configfdid_to_config = #{} :: #{} | #{integer() := term()},
script_name = {[],[]} :: {string(), string()}}).
-type state() :: #state{}.
%% Data for eval_script/2.
-record(es,
{init,
debug,
path,
pa,
pz,
path_choice,
prim_load,
load_mode,
vars
}).
-define(ON_LOAD_HANDLER, init__boot__on_load_handler).
debug(false, _) -> ok;
debug(_, T) -> erlang:display(T).
debug(false, _, Fun) ->
Fun();
debug(_, T, Fun) ->
erlang:display(T),
T1 = erlang:monotonic_time(),
Val = Fun(),
T2 = erlang:monotonic_time(),
Time = erlang:convert_time_unit(T2 - T1, native, microsecond),
erlang:display({done_in_microseconds, Time}),
Val.
-doc false.
-spec get_configfd(integer()) -> none | term().
get_configfd(ConfigFdId) ->
request({get_configfd, ConfigFdId}).
-doc false.
-spec set_configfd(integer(), term()) -> 'ok'.
set_configfd(ConfigFdId, Config) ->
request({set_configfd, ConfigFdId, Config}),
ok.
-doc """
Returns all command-line flags and the system-defined flags, see
`get_argument/1`.
""".
-spec get_arguments() -> Flags when
Flags :: [{Flag :: atom(), Values :: [string()]}].
get_arguments() ->
request(get_arguments).
-doc "Returns any plain command-line arguments as a list of strings (possibly empty).".
-spec get_plain_arguments() -> [Arg] when
Arg :: string().
get_plain_arguments() ->
bs2ss(request(get_plain_arguments)).
-doc """
Returns all values associated with the command-line user flag `Flag`.
If `Flag` is provided several times, each `Values` is returned in preserved order.
Example:
```erlang
% erl -a b c -a d
...
1> init:get_argument(a).
{ok,[["b","c"],["d"]]}
```
The following flags are defined automatically and can be retrieved using this
function:
- **`root`** - The installation directory of Erlang/OTP, `$ROOT`:
```text
2> init:get_argument(root).
{ok,[["/usr/local/otp/releases/otp_beam_solaris8_r10b_patched"]]}
```
- **`progname`** - The name of the program which started Erlang:
```erlang
3> init:get_argument(progname).
{ok,[["erl"]]}
```
- **`home`{: #home }** - The home directory (on Unix, the value of $HOME):
```erlang
4> init:get_argument(home).
{ok,[["/home/harry"]]}
```
Returns `error` if no value is associated with `Flag`.
""".
-spec get_argument(Flag) -> {'ok', Arg} | 'error' when
Flag :: atom(),
Arg :: [Values :: [string()]].
get_argument(Arg) ->
request({get_argument, Arg}).
-doc """
Gets the identity of the boot script used to boot the system.
`Id` can be any Erlang term. In the delivered boot scripts, `Id` is `{Name, Vsn}`.
`Name` and `Vsn` are strings.
""".
-spec script_id() -> Id when
Id :: term().
script_id() ->
request(script_id).
%% Returns the path to the boot script. The path can only be relative
%% (i.e., not absolute) if prim_file:get_cwd() returned an error tuple
%% during boot. filename:absname/2 is not available during boot so we
%% construct the path here instead of during boot
-doc false.
-spec script_name() -> string().
script_name() ->
{BootCWD, ScriptPath} = request(get_script_name),
case BootCWD of
[] ->
ScriptPath;
_ ->
%% Makes the path absolute if ScriptPath is a relative
%% path
filename:absname(ScriptPath, BootCWD)
end.
%% Module internal function to set the script name during boot
-spec set_script_name(BootCurrentWorkingDir, ScriptPath) -> 'ok' when
BootCurrentWorkingDir :: string(),
ScriptPath :: string().
set_script_name(BootCurrentWorkingDir, ScriptPath) ->
request({set_script_name, {BootCurrentWorkingDir, ScriptPath}}),
ok.
bs2as(L0) when is_list(L0) ->
map(fun b2a/1, L0);
bs2as(L) ->
L.
bs2ss(L0) when is_list(L0) ->
map(fun b2s/1, L0);
bs2ss(L) ->
L.
-doc """
The current status of the `init` process can be inspected.
During system startup (initialization), `InternalStatus` is `starting`, and
`ProvidedStatus` indicates how far the boot script has been interpreted. Each
`{progress, Info}` term interpreted in the boot script affects `ProvidedStatus`,
that is, `ProvidedStatus` gets the value of `Info`.
""".
-spec get_status() -> {InternalStatus, ProvidedStatus} when
InternalStatus :: internal_status(),
ProvidedStatus :: term().
get_status() ->
request(get_status).
-doc false.
-spec fetch_loaded() -> [{module(),file:filename()}].
fetch_loaded() ->
request(fetch_loaded).
%% Handle dynamic code loading until the
%% real code_server has been started.
-doc false.
-spec ensure_loaded(atom()) -> 'not_allowed' | {'module', atom()}.
ensure_loaded(Module) ->
request({ensure_loaded, Module}).
-doc false.
-spec make_permanent(file:filename(), 'false' | file:filename()) ->
'ok' | {'error', term()}.
make_permanent(Boot,Config) ->
request({make_permanent,Boot,Config}).
-doc false.
-spec notify_when_started(pid()) -> 'ok' | 'started'.
notify_when_started(Pid) ->
request({notify_when_started,Pid}).
-doc false.
-spec wait_until_started() -> 'ok'.
wait_until_started() ->
receive
{init,started} -> ok
end.
request(Req) ->
init ! {self(),Req},
receive
{init,Rep} ->
Rep
end.
-doc "The same as [`restart([])`](`restart/1`).".
-spec restart() -> 'ok'.
restart() -> restart([]).
-doc """
Restart all Erlang applications.
The system is restarted _inside_ the running Erlang node, which means that the
emulator is not restarted. All applications are taken down smoothly, all code is
unloaded, and all ports are closed before the system is booted again in the same
way as initially started.
The same `BootArgs` are used when restarting the system unless the `mode` option
is given, allowing the code loading mode to be set to either `embedded` or
`interactive`. All other `BootArgs` remain the same.
To limit the shutdown time, the time `init` is allowed to spend taking down
applications, command-line flag `-shutdown_time` is to be used.
""".
-doc(#{since => <<"OTP 23.0">>}).
-spec restart([{mode, mode()}]) -> 'ok'.
restart([]) ->
init ! {stop,restart}, ok;
restart([{mode, Mode}]) when Mode =:= embedded; Mode =:= interactive ->
init ! {stop,{restart,Mode}}, ok;
restart(Opts) when is_list(Opts) ->
erlang:error(badarg, [Opts]).
-doc """
Reboot the Erlang node.
All applications are taken down smoothly, all code is unloaded, and all ports
are closed before the system terminates.
If command-line flag `-heart` was specified, the `heart` program tries to reboot
the system. For more information, see `m:heart`.
To limit the shutdown time, the time `init` is allowed to spend taking down
applications, command-line flag `-shutdown_time` is to be used.
""".
-spec reboot() -> 'ok'.
reboot() -> init ! {stop,reboot}, ok.
-doc "The same as [`stop(0)`](`stop/1`).".
-spec stop() -> 'ok'.
stop() -> init ! {stop,stop}, ok.
-doc """
Stop the Erlang node.
All applications are taken down smoothly, all code is unloaded, and all ports
are closed before the system terminates by calling [`halt(Status)`](`halt/1`).
If command-line flag `-heart` was specified, the `heart` program is terminated
before the Erlang node terminates. For more information, see `m:heart`.
To limit the shutdown time, the time `init` is allowed to spend taking down
applications, command-line flag `-shutdown_time` is to be used.
""".
-spec stop(Status) -> 'ok' when
Status :: non_neg_integer() | string().
stop(Status) when is_integer(Status), Status >= 0 ->
stop_1(Status);
stop(Status) when is_list(Status) ->
case is_bytelist(Status) of
true ->
stop_1(Status);
false ->
erlang:error(badarg)
end;
stop(_) ->
erlang:error(badarg).
is_bytelist([B|Bs]) when is_integer(B), B >= 0, B < 256 -> is_bytelist(Bs);
is_bytelist([]) -> true;
is_bytelist(_) -> false.
%% Note that we check the type of Status beforehand to ensure that
%% the call to halt(Status) by the init process cannot fail
stop_1(Status) -> init ! {stop,{stop,Status}}, ok.
-doc """
Starts the Erlang runtime system.
This function is called when the emulator is started and coordinates system startup.
`BootArgs` are all command-line arguments except the emulator flags, that is,
flags and plain arguments; see [`erl(1)`](erl_cmd.md).
`init` interprets some of the flags, see section
[Command-Line Flags](`m:init#flags`) below. The remaining flags ("user flags")
and plain arguments are passed to the `init` loop and can be retrieved by
calling `get_arguments/0` and `get_plain_arguments/0`, respectively.
""".
-spec boot(BootArgs) -> no_return() when
BootArgs :: [binary()].
boot(BootArgs) ->
register(init, self()),
process_flag(trap_exit, true),
{Start,Flags,Args} = parse_boot_args(BootArgs),
%% We don't get to profile parsing of BootArgs
case b2a(get_flag(profile_boot, Flags, false)) of
false -> ok;
true -> debug_profile_start()
end,
boot(Start, Flags, Args).
fold_eval_args([Expr]) -> Expr;
fold_eval_args(Exprs) -> Exprs.
%% Ensure that when no arguments were explicitly passed on the command line,
%% an empty arguments list will be passed to the function to be applied.
interpolate_empty_mfa_args({M, F, []}) -> {M, F, [[]]};
interpolate_empty_mfa_args({_M, _F, [_Args]} = MFA) -> MFA.
-spec run_args_to_mfa([binary()]) -> {atom(), atom(), [] | [nonempty_list(binary())]} | no_return().
run_args_to_mfa([]) ->
erlang:display_string(
"Error! The -S option must be followed by at least a module to start, such as "
"`-S Module` or `-S Module Function` to start with a function.\r\n\r\n"
),
halt();
run_args_to_mfa([M]) -> {b2a(M), start, []};
run_args_to_mfa([M, F]) -> {b2a(M), b2a(F), []};
run_args_to_mfa([M, F | A]) -> {b2a(M), b2a(F), [A]}.
%% Convert -run / -s / -S arguments to startup instructions, such that
%% no instructions are emitted if no arguments follow the flag, otherwise,
%% an `{apply, M, F, A}' instruction is.
run_args_to_start_instructions([], _Converter) -> [];
run_args_to_start_instructions(Args, Converter) ->
{M, F, A} = run_args_to_mfa(Args),
[{apply, M, F, map(Converter, A)}].
b2a(Bin) when is_binary(Bin) ->
list_to_atom(b2s(Bin));
b2a(A) when is_atom(A) ->
A.
b2s(Bin) when is_binary(Bin) ->
try
unicode:characters_to_list(Bin,file:native_name_encoding())
catch
_:_ -> binary_to_list(Bin)
end;
b2s(L) when is_list(L) ->
L.
map(_F, []) ->
[];
map(F, [X|Rest]) ->
[F(X) | map(F, Rest)].
-doc false.
-spec code_path_choice() -> 'relaxed' | 'strict'.
code_path_choice() ->
case get_argument(code_path_choice) of
{ok,[["strict"]]} ->
strict;
{ok,[["relaxed"]]} ->
relaxed;
_Else ->
strict
end.
boot(Start,Flags,Args) ->
start_on_load_handler_process(),
BootPid = do_boot(Flags,Start),
State = #state{flags = Flags,
args = Args,
start = Start,
bootpid = BootPid},
boot_loop(BootPid,State).
things_to_string([X|Rest]) ->
" (" ++ erts_internal:term_to_string(X, 32768) ++ ")" ++
things_to_string(Rest);
things_to_string([]) ->
"".
halt_string(String, List) ->
String ++ things_to_string(List).
%% String = string()
%% List = [string() | atom() | pid() | number() | list() | tuple()]
%% Items in List are truncated if found to be too large
-spec crash(_, _) -> no_return().
crash(String, List) ->
halt(halt_string(String, List)).
%% Status is {InternalStatus,ProvidedStatus}
-spec boot_loop(pid(), state()) -> no_return().
boot_loop(BootPid, State) ->
receive
{BootPid,loaded,NewlyLoaded} ->
Loaded = NewlyLoaded ++ State#state.loaded,
boot_loop(BootPid, State#state{loaded = Loaded});
{BootPid,started,KernelPid} ->
boot_loop(BootPid, new_kernelpid(KernelPid, BootPid, State));
{BootPid,progress,started} ->
{InS,_} = State#state.status,
notify(State#state.subscribed),
boot_loop(BootPid,State#state{status = {InS,started},
subscribed = []});
{BootPid,progress,NewStatus} ->
{InS,_} = State#state.status,
boot_loop(BootPid,State#state{status = {InS,NewStatus}});
{BootPid,{script_id,Id}} ->
boot_loop(BootPid,State#state{script_id = Id});
{'EXIT',BootPid,normal} ->
{_,PS} = State#state.status,
notify(State#state.subscribed),
loop(State#state{status = {started,PS},
subscribed = []});
{'EXIT',BootPid,Reason} ->
% erlang:display({"init terminating in do_boot",Reason}),
crash("Runtime terminating during boot", [Reason]);
{'EXIT',Pid,Reason} ->
Kernel = State#state.kernel,
terminate(Pid,Kernel,Reason), %% If Pid is a Kernel pid, halt()!
boot_loop(BootPid,State);
{stop,Reason} ->
stop(Reason,State);
{From,fetch_loaded} -> %% Fetch and reset initially loaded modules.
From ! {init,State#state.loaded},
garb_boot_loop(BootPid,State#state{loaded = []});
{From,{ensure_loaded,Module}} ->
{Res, Loaded} = ensure_loaded(Module, State#state.loaded),
From ! {init,Res},
boot_loop(BootPid,State#state{loaded = Loaded});
Msg ->
boot_loop(BootPid,handle_msg(Msg,State))
end.
ensure_loaded(Module, Loaded) ->
case erlang:module_loaded(Module) of
true ->
{{module, Module}, Loaded};
false ->
do_ensure_loaded(Module, Loaded)
end.
do_ensure_loaded(Module, Loaded) ->
File = atom_to_list(Module) ++ objfile_extension(),
case erl_prim_loader:get_file(File) of
{ok,BinCode,FullName} ->
case do_load_module(Module, BinCode) of
ok ->
{{module, Module}, [{Module, FullName}|Loaded]};
error ->
{error, [{Module, FullName}|Loaded]}
end;
Error ->
{Error, Loaded}
end.
%% Tell subscribed processes the system has started.
notify(Pids) ->
lists:foreach(fun(Pid) -> Pid ! {init,started} end, Pids).
%% Garbage collect all info about initially loaded modules.
%% This information is temporarily stored until the code_server
%% is started.
%% We force the garbage collection as the init process holds
%% this information during the initialisation of the system and
%% it will be automatically garbed much later (perhaps not at all
%% if it is not accessed much).
garb_boot_loop(BootPid,State) ->
garbage_collect(),
boot_loop(BootPid,State).
new_kernelpid({Name,{ok,Pid}},BootPid,State) when is_pid(Pid) ->
link(Pid),
BootPid ! {self(),ok,Pid},
Kernel = State#state.kernel,
State#state{kernel = [{Name,Pid}|Kernel]};
new_kernelpid({_Name,ignore},BootPid,State) ->
BootPid ! {self(),ignore},
State;
new_kernelpid({Name,What},BootPid,State) ->
% erlang:display({"could not start kernel pid",Name,What}),
clear_system(false,BootPid,State),
crash("Could not start kernel pid", [Name, What]).
%% Here is the main loop after the system has booted.
loop(State) ->
receive
{'EXIT',Pid,Reason} ->
Kernel = State#state.kernel,
terminate(Pid,Kernel,Reason), %% If Pid is a Kernel pid, halt()!
loop(State);
{stop,Reason} ->
stop(Reason,State);
{From,fetch_loaded} -> %% The Loaded info is cleared in
Loaded = State#state.loaded, %% boot_loop but is handled here
From ! {init,Loaded}, %% anyway.
loop(State);
Msg ->
loop(handle_msg(Msg,State))
end.
handle_msg(Msg,State0) ->
case catch do_handle_msg(Msg,State0) of
{new_state,State} -> State;
_ -> State0
end.
do_handle_msg(Msg,State) ->
#state{flags = Flags,
status = Status,
script_id = Sid,
args = Args,
subscribed = Subscribed,
configfdid_to_config = ConfigFdIdToConfig,
script_name = ScriptName} = State,
case Msg of
{From,get_plain_arguments} ->
From ! {init,Args};
{From,get_arguments} ->
From ! {init,get_arguments(Flags)};
{From,{get_argument,Arg}} ->
From ! {init,get_argument(Arg,Flags)};
{From,get_status} ->
From ! {init,Status};
{From,script_id} ->
From ! {init,Sid};
{From,{make_permanent,Boot,Config}} ->
{Res,State1} = make_permanent(Boot,Config,Flags,State),
From ! {init,Res},
{new_state,State1};
{From,{notify_when_started,Pid}} ->
case Status of
{InS,PS} when InS =:= started ; PS =:= started ->
From ! {init,started};
_ ->
From ! {init,ok},
{new_state,State#state{subscribed = [Pid|Subscribed]}}
end;
{From, {ensure_loaded, _}} ->
From ! {init, not_allowed};
{From, {get_configfd, ConfigFdId}} ->
case ConfigFdIdToConfig of
#{ConfigFdId := Config} ->
From ! {init, Config};
_ ->
From ! {init, none}
end;
{From, {set_configfd, ConfigFdId, Config}} ->
From ! {init, ok},
NewConfigFdIdToConfig = ConfigFdIdToConfig#{ConfigFdId => Config},
NewState = State#state{configfdid_to_config = NewConfigFdIdToConfig},
{new_state, NewState};
{From, get_script_name} ->
From ! {init, ScriptName};
{From, {set_script_name, NewScriptName}} ->
From ! {init, ok},
NewState = State#state{script_name = NewScriptName},
{new_state, NewState};
X ->
case whereis(user) of
%% io_requests may end up here from various processes that have
%% init as their group_leader. Most notably all application_master
%% processes have init as their gl, though they will short-circuit
%% to `user` if possible.
User when element(1, X) =:= io_request,
User =/= undefined ->
User ! X;
_ ->
%% Only call the logger module if the logger_server is running.
%% If it is not running, then we don't know that the logger
%% module can be loaded.
case whereis(logger) =/= undefined of
true -> logger:info("init got unexpected: ~p", [X],
#{ error_logger=>#{tag=>info_msg}});
false ->
erlang:display_string(stdout, "init got unexpected: "),
erlang:display(X)
end
end
end.
%%% -------------------------------------------------
%%% A new release has been installed and made
%%% permanent.
%%% Both restart/0 and reboot/0 shall startup using
%%% the new release. reboot/0 uses new boot script
%%% and configuration file pointed out externally.
%%% In the restart case we have to set new -boot and
%%% -config arguments.
%%% -------------------------------------------------
make_permanent(Boot,Config,Flags0,State) ->
case set_flag(boot, Boot, Flags0) of
{ok,Flags1} ->
case set_flag(config, Config, Flags1) of
{ok,Flags} ->
{ok,State#state{flags = Flags}};
Error ->
{Error,State}
end;
Error ->
{Error,State}
end.
set_flag(_Flag,false,Flags) ->
{ok,Flags};
set_flag(Flag,Value,Flags) when is_list(Value) ->
%% The flag here can be -boot or -config, which means the value is
%% a file name! Thus the file name encoding is used when converting.
Encoding = file:native_name_encoding(),
case catch unicode:characters_to_binary(Value,Encoding,Encoding) of
{'EXIT',_} ->
{error,badarg};
AValue ->
{ok,set_argument(Flags,Flag,AValue)}
end;
set_flag(_,_,_) ->
{error,badarg}.
%%% -------------------------------------------------
%%% Stop the system.
%%% Reason is: restart | {restart, Mode} | reboot | stop
%%% According to reason terminate emulator or restart
%%% system using the same init process again.
%%% -------------------------------------------------
stop(Reason,State) ->
BootPid = State#state.bootpid,
{_,Progress} = State#state.status,
State1 = State#state{status = {stopping, Progress}},
clear_system(should_unload(Reason),BootPid,State1),
do_stop(Reason,State1).
%% There is no need to unload code if the system is shutting down
should_unload(stop) -> false;
should_unload({stop, _}) -> false;
should_unload(_) -> true.
do_stop({restart,Mode},#state{start=Start, flags=Flags0, args=Args}) ->
Flags = update_flag(mode, Flags0, atom_to_binary(Mode)),
do_restart(Start,Flags,Args);
do_stop(restart,#state{start=Start, flags=Flags, args=Args}) ->
do_restart(Start,Flags,Args);
do_stop(reboot,_) ->
halt();
do_stop(stop,State) ->
stop_heart(State),
halt();
do_stop({stop,Status},State) ->
stop_heart(State),
halt(Status).
do_restart(Start,Flags,Args) ->
flush(),
erl_init:restart(),
boot(Start,Flags,Args).
clear_system(Unload,BootPid,State) ->
Heart = get_heart(State#state.kernel),
Logger = get_logger(State#state.kernel),
shutdown_pids(Heart,Logger,BootPid,State),
Unload andalso unload(Heart),
kill_em([Logger]),
Unload andalso do_unload([logger_server]).
flush() ->
receive
_M -> flush()
after 0 ->
ok
end.
stop_heart(State) ->
case get_heart(State#state.kernel) of
false ->
ok;
Pid ->
%% As heart survives a restart the Parent of heart is init.
BootPid = self(),
%% ignore timeout
shutdown_kernel_pid(Pid, BootPid, self(), State)
end.
shutdown_pids(Heart,Logger,BootPid,State) ->
Timer = shutdown_timer(State#state.flags),
global_prepare_shutdown(),
catch shutdown(State#state.kernel,BootPid,Timer,State),
kill_all_pids(Heart,Logger), % Even the shutdown timer.
kill_all_ports(Heart), % Logger has no ports
flush_timout(Timer).
global_prepare_shutdown() ->
%% Inform global that we are shutting down, so it wont
%% send 'lost_connection' messages when connections
%% goes down...
case whereis(global_name_server) of
undefined ->
ok;
Pid ->
Mon = erlang:monitor(process, Pid),
Pid ! {prepare_shutdown, self(), Mon},
receive
{Mon, ok} ->
erlang:demonitor(Mon, [flush]),
ok;
{'DOWN', Mon, process, Pid, _Reason} ->
ok
end
end.
get_heart(Kernel) ->
get_kernelpid(heart,Kernel).