forked from rurban/perl-compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathC.pm
6842 lines (6279 loc) · 228 KB
/
C.pm
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
# C.pm
#
# Copyright (c) 1996, 1997, 1998 Malcolm Beattie
# Copyright (c) 2008, 2009, 2010, 2011 Reini Urban
# Copyright (c) 2010 Nick Koston
# Copyright (c) 2011, 2012 cPanel Inc
#
# You may distribute under the terms of either the GNU General Public
# License or the Artistic License, as specified in the README file.
#
package B::C;
use strict;
our $VERSION = '1.43';
my %debug;
our $check;
my $eval_pvs = '';
package B::C::Section;
use strict;
use B ();
use base 'B::Section';
sub new {
my $class = shift;
my $o = $class->SUPER::new(@_);
push @$o, { values => [] };
return $o;
}
sub add {
my $section = shift;
push( @{ $section->[-1]{values} }, @_ );
}
sub remove {
my $section = shift;
pop @{ $section->[-1]{values} };
}
sub index {
my $section = shift;
return scalar( @{ $section->[-1]{values} } ) - 1;
}
sub comment {
my $section = shift;
$section->[-1]{comment} = join( "", @_ ) if @_;
$section->[-1]{comment};
}
# add debugging info - stringified flags on -DF
sub debug {
my $section = shift;
my $dbg = join( " ", @_ );
$section->[-1]{dbg}->[ $section->index ] = $dbg if $dbg;
}
sub output {
my ( $section, $fh, $format ) = @_;
my $sym = $section->symtable || {};
my $default = $section->default;
return if $B::C::check;
my $i = 0;
my $dodbg = 1 if $debug{flags} and $section->[-1]{dbg};
foreach ( @{ $section->[-1]{values} } ) {
my $dbg = "";
my $ref = "";
if (m/(s\\_[0-9a-f]+)/) {
if (!exists($sym->{$1}) and $1 ne 's\_0') {
$ref = $1;
$B::C::unresolved_count++;
warn "Warning: unresolved ".$section->name." symbol $ref\n" if $B::C::verbose;
}
}
s{(s\\_[0-9a-f]+)}{ exists($sym->{$1}) ? $sym->{$1} : $default; }ge;
if ($dodbg and $section->[-1]{dbg}->[$i]) {
$dbg = " /* ".$section->[-1]{dbg}->[$i]." ".$ref." */";
}
printf $fh $format, $_, $section->name, $i, $ref, $dbg;
++$i;
}
}
package B::C::InitSection;
use strict;
# avoid use vars
@B::C::InitSection::ISA = qw(B::C::Section);
sub new {
my $class = shift;
my $max_lines = 10000; #pop;
my $section = $class->SUPER::new(@_);
$section->[-1]{evals} = [];
$section->[-1]{initav} = [];
$section->[-1]{chunks} = [];
$section->[-1]{nosplit} = 0;
$section->[-1]{current} = [];
$section->[-1]{count} = 0;
$section->[-1]{max_lines} = $max_lines;
return $section;
}
sub split {
my $section = shift;
$section->[-1]{nosplit}--
if $section->[-1]{nosplit} > 0;
}
sub no_split {
shift->[-1]{nosplit}++;
}
sub inc_count {
my $section = shift;
$section->[-1]{count} += $_[0];
# this is cheating
$section->add();
}
sub add {
my $section = shift->[-1];
my $current = $section->{current};
my $nosplit = $section->{nosplit};
push @$current, @_;
$section->{count} += scalar(@_);
if ( !$nosplit && $section->{count} >= $section->{max_lines} ) {
push @{ $section->{chunks} }, $current;
$section->{current} = [];
$section->{count} = 0;
}
}
sub add_eval {
my $section = shift;
my @strings = @_;
foreach my $i (@strings) {
$i =~ s/\"/\\\"/g;
}
push @{ $section->[-1]{evals} }, @strings;
}
sub add_initav {
my $section = shift;
push @{ $section->[-1]{initav} }, @_;
}
sub output {
my ( $section, $fh, $format, $init_name ) = @_;
my $sym = $section->symtable || {};
my $default = $section->default;
return if $B::C::check;
push @{ $section->[-1]{chunks} }, $section->[-1]{current};
my $name = "aaaa";
foreach my $i ( @{ $section->[-1]{chunks} } ) {
# dTARG and dSP unused -nt
print $fh <<"EOT";
static int ${init_name}_${name}(pTHX)
{
EOT
foreach my $i ( @{ $section->[-1]{initav} } ) {
print $fh "\t",$i,"\n";
}
foreach my $j (@$i) {
$j =~ s{(s\\_[0-9a-f]+)}
{ exists($sym->{$1}) ? $sym->{$1} : $default; }ge;
print $fh "\t$j\n";
}
print $fh "\treturn 0;\n}\n";
$section->SUPER::add("${init_name}_${name}(aTHX);");
++$name;
}
$section->SUPER::add("perl_init2(aTHX);") unless $init_name eq 'perl_init2';
# We need to output evals after dl_init.
foreach my $s ( @{ $section->[-1]{evals} } ) {
${B::C::eval_pvs} .= " eval_pv(\"$s\",1);\n";
}
print $fh "static int ${init_name}(pTHX)
{";
$section->SUPER::output( $fh, $format );
print $fh "\treturn 0;\n}\n";
}
package B::C;
use strict;
use Exporter ();
use Errno (); #needed since 5.14
our %Regexp;
{ # block necessary for caller to work
my $caller = caller;
if ( $caller eq 'O' or $caller eq 'Od' ) {
require XSLoader;
XSLoader::load('B::C'); # for r-magic only
}
}
our @ISA = qw(Exporter);
our @EXPORT_OK =
qw( output_all output_boilerplate output_main output_main_rest mark_unused mark_skip
init_sections set_callback save_unused_subs objsym save_context fixup_ppaddr
save_sig svop_pv inc_cleanup ivx nvx );
# for 5.6 better use the native B::C
# 5.6.2 works fine though.
use B
qw( minus_c sv_undef walkoptree walkoptree_slow walksymtable main_root main_start peekop
class cchar svref_2object compile_stats comppadlist hash
threadsv_names main_cv init_av end_av opnumber cstring
HEf_SVKEY SVf_POK SVf_ROK SVf_IOK SVf_NOK SVf_IVisUV SVf_READONLY );
BEGIN {
if ($] >= 5.008) {
@B::NV::ISA = 'B::IV'; # add IVX to nv. This fixes test 23 for Perl 5.8
B->import(qw(regex_padav SVp_NOK SVp_IOK CVf_CONST CVf_ANON)); # both unsupported for 5.6
} else {
eval q[
sub SVp_NOK() {0}; # unused
sub SVp_IOK() {0};
sub CVf_ANON() {4};
];
@B::PVMG::ISA = qw(B::PVNV B::RV);
}
if ($] >= 5.010) {
require mro; mro->import;
sub SVf_OOK() { 0x02000000 }; # not exported
}
}
use B::Asmdata qw(@specialsv_name);
use B::C::Flags;
use FileHandle;
use Config;
my $hv_index = 0;
my $gv_index = 0;
my $re_index = 0;
my $pv_index = 0;
my $cv_index = 0;
my $hek_index = 0;
my $anonsub_index = 0;
my $initsub_index = 0;
my $padlist_index = 0;
# exclude all not B::C:: prefixed subs
my %all_bc_subs = map { $_ => 1 }
qw(B::AV::save B::BINOP::save B::BM::save
B::COP::save B::CV::save B::FAKEOP::fake_ppaddr B::FAKEOP::flags
B::FAKEOP::new B::FAKEOP::next B::FAKEOP::ppaddr B::FAKEOP::private
B::FAKEOP::save B::FAKEOP::sibling B::FAKEOP::targ B::FAKEOP::type
B::GV::save B::GV::savecv B::HV::save B::IO::save B::IO::save_data
B::IV::save B::LISTOP::save B::LOGOP::save B::LOOP::save B::NULL::save
B::NV::save B::OBJECT::save B::OP::_save_common B::OP::fake_ppaddr
B::OP::isa B::OP::save B::PADLIST::save B::PADOP::save B::PMOP::save B::PV::save
B::PVIV::save B::PVLV::save B::PVMG::save B::PVMG::save_magic
B::PVNV::save B::PVOP::save B::REGEXP::save B::RV::save B::SPECIAL::save
B::SPECIAL::savecv B::SV::save B::SVOP::save B::UNOP::save B::UV::save
B::REGEXP::EXTFLAGS
);
# Track all internally used packages. All others may not be deleted automatically
# - hidden methods. -fdelete-pkg
my %all_bc_pkg = map { $_ => 1 }
qw(B B::AV B::BINOP B::BM B::COP B::CV B::FAKEOP
B::GV B::HV B::IO B::IV B::LISTOP B::LOGOP B::LOOP B::NULL B::NV
B::OBJECT B::OP B::PADOP B::PMOP B::PV B::PVIV B::PVLV B::PVMG B::PVNV
B::PVOP B::REGEXP B::RV B::SPECIAL B::SV B::SVOP B::UNOP B::UV
AnyDBM_File Fcntl Regexp overload Errno Exporter Exporter::Heavy Config
warnings warnings::register DB next maybe maybe::next FileHandle fields
AutoLoader Carp Symbol PerlIO PerlIO::scalar SelectSaver ExtUtils
ExtUtils::Constant ExtUtils::Constant::ProxySubs threads base IO::File
IO::Seekable IO::Handle IO DynaLoader XSLoader O
);
# Note: BEGIN-time sideffect-only packages like strict, vars or constant even
# without functions should not be deleted, so they are not listed here.
# Keep: vars strict constant
if (exists $INC{'blib.pm'}) { # http://blogs.perl.org/users/rurban/2012/02/the-unexpected-case-of--mblib.html
for (qw(Cwd File File::Spec File::Spec::Unix Dos EPOC blib Scalar
Scalar::Util VMS VMS::Filespec VMS::Feature Win32)) {
$all_bc_pkg{$_} = 1;
}
}
# B::C stash footprint: mainly caused by blib, warnings, and Carp loaded with DynaLoader
# perl5.15.7d-nt -MO=C,-o/dev/null -MO=Stash -e0
# -umain,-ure,-umro,-ustrict,-uAnyDBM_File,-uFcntl,-uRegexp,-uoverload,-uErrno,-uExporter,-uExporter::Heavy,-uConfig,-uwarnings,-uwarnings::register,-uDB,-unext,-umaybe,-umaybe::next,-uFileHandle,-ufields,-uvars,-uAutoLoader,-uCarp,-uSymbol,-uPerlIO,-uPerlIO::scalar,-uSelectSaver,-uExtUtils,-uExtUtils::Constant,-uExtUtils::Constant::ProxySubs,-uthreads,-ubase
# perl5.15.7d-nt -MErrno -MO=Stash -e0
# -umain,-ure,-umro,-ustrict,-uRegexp,-uoverload,-uErrno,-uExporter,-uExporter::Heavy,-uwarnings,-uwarnings::register,-uConfig,-uDB,-uvars,-uCarp,-uPerlIO,-uthreads
# perl5.15.7d-nt -Mblib -MO=Stash -e0
# -umain,-ure,-umro,-ustrict,-uCwd,-uRegexp,-uoverload,-uFile,-uFile::Spec,-uFile::Spec::Unix,-uDos,-uExporter,-uExporter::Heavy,-uConfig,-uwarnings,-uwarnings::register,-uDB,-uEPOC,-ublib,-uScalar,-uScalar::Util,-uvars,-uCarp,-uVMS,-uVMS::Filespec,-uVMS::Feature,-uWin32,-uPerlIO,-uthreads
# perl -MO=Stash -e0
# -umain,-uTie,-uTie::Hash,-ure,-umro,-ustrict,-uRegexp,-uoverload,-uExporter,-uExporter::Heavy,-uwarnings,-uDB,-uCarp,-uPerlIO,-uthreads
# pb -MB::Stash -e0
# -umain,-ure,-umro,-uRegexp,-uPerlIO,-uExporter,-uDB
my ($package_pv, @package_pv); # global stash for methods since 5.13
my (%symtable, %cvforward, %lexwarnsym);
my (%strtable, %hektable, @static_free, %newpkg);
my %xsub;
my ($warn_undefined_syms, $method_named_warn);
my ($staticxs, $outfile);
my (%include_package, %skip_package, %saved, %isa_cache, %method_cache);
my %static_ext;
my ($use_xsloader);
my $nullop_count = 0;
my $unresolved_count = 0;
# options and optimizations shared with B::CC
our ($curcv, $module, $init_name, %savINC, $mainfile);
our ($use_av_undef_speedup, $use_svpop_speedup) = (1, 1);
our ($pv_copy_on_grow, $optimize_ppaddr, $optimize_warn_sv, $use_perl_script_name,
$save_data_fh, $save_sig, $optimize_cop, $av_init, $av_init2, $ro_inc, $destruct,
$fold, $warnings, $const_strings, $stash, $can_delete_pkg, $walkall);
our $verbose = 0;
our %option_map = (
'cog' => \$B::C::pv_copy_on_grow,
'const-strings' => \$B::C::const_strings,
'save-data' => \$B::C::save_data_fh,
'ppaddr' => \$B::C::optimize_ppaddr,
'warn-sv' => \$B::C::optimize_warn_sv,
'av-init' => \$B::C::av_init,
'av-init2' => \$B::C::av_init2,
'ro-inc' => \$B::C::ro_inc,
'delete-pkg' => \$B::C::can_delete_pkg,
'walkall' => \$B::C::walkall,
'stash' => \$B::C::stash, # disable with -fno-stash
'destruct' => \$B::C::destruct, # disable with -fno-destruct
'fold' => \$B::C::fold, # disable with -fno-fold
'warnings' => \$B::C::warnings, # disable with -fno-warnings
'use-script-name' => \$use_perl_script_name,
'save-sig-hash' => \$B::C::save_sig,
'cop' => \$optimize_cop, # XXX very unsafe!
# Better do it in CC, but get rid of
# NULL cops also there.
);
our %debug_map = (
'O' => 'op',
'A' => 'av',
'H' => 'hv',
'C' => 'cv',
'M' => 'mg',
'R' => 'rx',
'G' => 'gv',
'S' => 'sv',
'w' => 'walk',
'c' => 'cops',
's' => 'sub',
'p' => 'pkg',
'm' => 'meth',
'u' => 'unused',
);
my @xpvav_sizes;
my ($max_string_len, $in_endav);
my %static_core_pkg; # = map {$_ => 1} static_core_packages();
my $MULTI = $Config{usemultiplicity};
my $ITHREADS = $Config{useithreads};
my $DEBUGGING = ($Config{ccflags} =~ m/-DDEBUGGING/);
my $PERL514 = ( $] >= 5.013002 );
my $PERL512 = ( $] >= 5.011 );
my $PERL510 = ( $] >= 5.009005 );
my $PERL56 = ( $] < 5.008001 ); # yes. 5.8.0 is a 5.6.x
# Thanks to Mattia Barbon for the C99 tip to init any union members
my $C99 = $Config{d_c99_variadic_macros}; # http://docs.sun.com/source/819-3688/c99.app.html#pgfId-1003962
my $MAD = $Config{mad};
my $MYMALLOC = $Config{usemymalloc} eq 'define';
my @threadsv_names;
BEGIN {
@threadsv_names = threadsv_names();
}
# This the Carp free workaround for DynaLoader::bootstrap
sub DynaLoader::croak {die @_}
# 5.15.3 workaround [perl #101336], without .bs support
# XSLoader::load_file($module, $modlibname, ...)
sub XSLoader::load_file {
#package DynaLoader;
use Config ();
my $module = shift or die "missing module name";
my $modlibname = shift or die "missing module filepath";
print STDOUT "XSLoader::load_file(\"$module\", \"$modlibname\" @_)\n"
if ${DynaLoader::dl_debug};
push @_, $module;
#if (my $ver = ${$module."::VERSION"}) {
# # XXX Ensure that there is no v-magic attached,. Else xs_version_bootcheck will fail.
# push @_, $ver;
#}
# works with static linking too
my $boots = "$module\::bootstrap";
goto &$boots if defined &$boots;
my @modparts = split(/::/,$module); # crashes threaded, issue 100
my $modfname = $modparts[-1];
my $modpname = join('/',@modparts);
my $c = @modparts;
$modlibname =~ s,[\\/][^\\/]+$,, while $c--; # Q&D basename
die "missing module filepath" unless $modlibname;
die "missing dlext" unless $Config::Config{dlext};
my $file = "$modlibname/auto/$modpname/$modfname.".$Config::Config{dlext};
# skip the .bs "bullshit" part, needed for some old solaris ages ago
goto \&DynaLoader::bootstrap_inherit if not -f $file;
my $bootname = "boot_$module";
$bootname =~ s/\W/_/g;
@DynaLoader::dl_require_symbols = ($bootname);
my $boot_symbol_ref;
if ($boot_symbol_ref = DynaLoader::dl_find_symbol(0, $bootname)) {
goto boot; #extension library has already been loaded, e.g. darwin
}
# Many dynamic extension loading problems will appear to come from
# this section of code: XYZ failed at line 123 of DynaLoader.pm.
# Often these errors are actually occurring in the initialisation
# C code of the extension XS file. Perl reports the error as being
# in this perl code simply because this was the last perl code
# it executed.
my $libref = DynaLoader::dl_load_file($file, 0) or do {
die("Can't load '$file' for module $module: " . DynaLoader::dl_error());
};
push(@DynaLoader::dl_librefs, $libref); # record loaded object
my @unresolved = DynaLoader::dl_undef_symbols();
if (@unresolved) {
die("Undefined symbols present after loading $file: @unresolved\n");
}
$boot_symbol_ref = DynaLoader::dl_find_symbol($libref, $bootname) or do {
die("Can't find '$bootname' symbol in $file\n");
};
push(@DynaLoader::dl_modules, $module); # record loaded module
boot:
my $xs = DynaLoader::dl_install_xsub($boots, $boot_symbol_ref, $file);
# See comment block above
push(@DynaLoader::dl_shared_objects, $file); # record files loaded
return &$xs(@_);
}
# Code sections
my (
$init, $decl, $symsect, $binopsect, $condopsect,
$copsect, $padopsect, $listopsect, $logopsect, $loopsect,
$opsect, $pmopsect, $pvopsect, $svopsect, $unopsect,
$svsect, $xpvsect, $xpvavsect, $xpvhvsect, $xpvcvsect,
$xpvivsect, $xpvuvsect, $xpvnvsect, $xpvmgsect, $xpvlvsect,
$xrvsect, $xpvbmsect, $xpviosect, $heksect, $free,
$padlistsect, $init2
);
my @op_sections = \(
$binopsect, $condopsect, $copsect, $padopsect,
$listopsect, $logopsect, $loopsect, $opsect,
$pmopsect, $pvopsect, $svopsect, $unopsect
);
sub walk_and_save_optree;
my $saveoptree_callback = \&walk_and_save_optree;
sub set_callback { $saveoptree_callback = shift }
sub saveoptree { &$saveoptree_callback(@_) }
sub save_main_rest;
sub verbose { if (@_) { $verbose = shift; } else { $verbose; } }
sub module { if (@_) { $module = shift; } else { $module; } }
sub walk_and_save_optree {
my ( $name, $root, $start ) = @_;
if ($root) {
$verbose ? walkoptree_slow( $root, "save" ) : walkoptree( $root, "save" );
}
return objsym($start);
}
# Look this up here so we can do just a number compare
# rather than looking up the name of every BASEOP in B::OP
my $OP_THREADSV = opnumber('threadsv');
my $OP_DBMOPEN = opnumber('dbmopen');
# special handling for nullified COP's.
my %OP_COP = ( opnumber('nextstate') => 1 );
$OP_COP{ opnumber('setstate') } = 1 if $] > 5.005003 and $] < 5.005062;
$OP_COP{ opnumber('dbstate') } = 1 unless $PERL512;
warn %OP_COP if $debug{cops};
# scalar: pv. list: (stash,pv,sv)
# pads are not named, but may be typed
sub padop_name {
my $op = shift;
my $cv = shift;
if ($op->can('name')
and ($op->name eq 'padsv' or $op->name eq 'method_named'
or ref($op) eq 'B::SVOP')) #threaded
{
return () if $cv and ref($cv->PADLIST) eq 'B::SPECIAL';
my @c = ($cv and ref($cv) eq 'B::CV' and ref($cv->PADLIST) ne 'B::NULL')
? $cv->PADLIST->ARRAY : comppadlist->ARRAY;
my @pad = $c[1]->ARRAY;
my @types = $c[0]->ARRAY;
my $ix = $op->can('padix') ? $op->padix : $op->targ;
my $sv = $pad[$ix];
my $t = $types[$ix];
if (defined($t) and ref($t) ne 'B::SPECIAL') {
my $pv = $sv->can("PV") ? $sv->PV : ($t->can('PVX') ? $t->PVX : '');
# need to fix B for SVpad_TYPEDI without formal STASH
my $stash = (ref($t) eq 'B::PVMG' and ref($t->SvSTASH) ne 'B::SPECIAL') ? $t->SvSTASH->NAME : '';
return wantarray ? ($stash,$pv,$sv) : $pv;
} elsif ($sv) {
my $pv = $sv->PV if $sv->can("PV");
my $stash = $sv->STASH->NAME if $sv->can("STASH");
return wantarray ? ($stash,$pv,$sv) : $pv;
}
}
}
sub svop_name {
my $op = shift;
my $cv = shift;
my $sv;
if ($op->can('name') and $op->name eq 'padsv') {
my @r = padop_name($op, $cv);
return wantarray ? @r : ($r[1] ? $r[1] : $r[0]);
} else {
if (!$op->can("sv")) {
if (ref($op) eq 'B::PMOP' and $op->pmreplroot->can("sv")) {
$sv = $op->pmreplroot->sv;
} else {
$sv = $op->first->sv unless $op->flags & 4
or ($op->name eq 'const' and $op->flags & 34) or $op->first->can("sv");
}
} else {
$sv = $op->sv;
}
if ($sv and $$sv) {
if ($sv->FLAGS & SVf_ROK) {
return '' if $sv->isa("B::NULL");
my $rv = $sv->RV;
if ($rv->isa("B::PVGV")) {
my $o = $rv->IO;
return $o->STASH->NAME if $$o;
}
return '' if $rv->isa("B::PVMG");
return $rv->STASH->NAME;
} else {
if ($op->name eq 'gvsv') {
return wantarray ? ($sv->STASH->NAME, $sv->NAME) : $sv->STASH->NAME.'::'.$sv->NAME;
} elsif ($op->name eq 'gv') {
return wantarray ? ($sv->STASH->NAME, $sv->NAME) : $sv->STASH->NAME.'::'.$sv->NAME;
} else {
return $sv->can('STASH') ? $sv->STASH->NAME
: $sv->can('NAME') ? $sv->NAME : $sv->PV;
}
}
}
}
}
# Returns a SVOP->pv (const PV or method_named PV mostly). for the symbol and stash name see svop_name
# 1. called from check_entersub/method_named to get the pv
# 2. called from svop before method/method_named to cache the $package_pv
sub svop_pv {
my $op = shift;
my $cv = shift;
my $sv;
if (!$op->can("sv")) {
if ($op->can('name') and $op->name eq 'padsv') {
my $pv = padop_name($op, $cv);
return $pv;
}
if (ref($op) eq 'B::PMOP' and $op->pmreplroot->can("sv")) {
$sv = $op->pmreplroot->sv;
} else {
if ($op->flags & 4 # OPf_KIDS
and !($op->name eq 'const' and $op->flags & 64) # !OPpCONST_BARE
and $op->first->can("sv")) {
$sv = $op->first->sv;
}
}
} else {
$sv = $op->sv;
}
if ($sv and $$sv) {
return $sv->PV if $sv->can("PV");
} else { # threaded
my $pv = padop_name($op, $cv);
return $pv;
}
}
# get or set package name for a variable, defined by
# $obj = bless {}, "Package"; or
# $obj = new Package; resp. $obj = Package->new;
# obj can be a padsv or gvsv
sub cache_svop_pkg {
my $svop = shift;
my $sv;
if ($svop->name eq 'padsv') {
my @c = comppadlist->ARRAY;
my @pad = $c[1]->ARRAY;
my $ix = $svop->can('padix') ? $svop->padix : $svop->targ;
$sv = $pad[$ix];
} elsif ($svop->name eq 'gvsv') {
$sv = $svop->sv;
} elsif ($svop->name eq 'gv') {
$sv = $svop->gv;
}
if ($sv and $$sv) {
if (@_) { # set
$newpkg{$$sv} = shift;
} else { # get
return $newpkg{$$sv};
}
}
}
sub savesym {
my ( $obj, $value ) = @_;
my $sym = sprintf( "s\\_%x", $$obj );
$symtable{$sym} = $value;
return $value;
}
sub objsym {
my $obj = shift;
return $symtable{ sprintf( "s\\_%x", $$obj ) };
}
sub getsym {
my $sym = shift;
my $value;
return 0 if $sym eq "sym_0"; # special case
if ( exists $symtable{$sym} ) {
return $symtable{$sym};
}
else {
warn "warning: undefined symbol $sym\n" if $warn_undefined_syms;
return "UNUSED";
}
}
sub delsym {
my ( $obj ) = @_;
my $sym = sprintf( "s\\_%x", $$obj );
delete $symtable{$sym};
}
sub savere {
my $re = shift;
my $flags = shift || 0;
my $sym;
my $pv = $re;
my $cur = length $pv;
my $len = 0; # length( pack "a*", $pv ) + 1;
if ($PERL514) {
$xpvsect->add( sprintf( "Nullhv, {0}, %u, %u", $cur, $len ) );
$svsect->add( sprintf( "&xpv_list[%d], 1, %x, {(char*)%s}", $xpvsect->index,
0x4405, savepv($pv) ) );
$sym = sprintf( "&sv_list[%d]", $svsect->index );
}
elsif ($PERL510) {
# BUG! Should be the same as newSVpvn($resym, $relen) but is not
my $s1 = ($PERL514 ? "NULL," : "") . "{0}, %u, %u";
$xpvsect->add( sprintf( $s1, $cur, $len ) );
$svsect->add( sprintf( "&xpv_list[%d], 1, %x, {(char*)%s}", $xpvsect->index,
0x4405, savepv($pv) ) );
my $s = "sv_list[".$svsect->index."]";
$sym = "&$s";
push @static_free, $s if $len and $B::C::pv_copy_on_grow;
}
else {
$sym = sprintf( "re%d", $re_index++ );
$decl->add( sprintf( "Static const char *$sym = %s;", cstring($re) ) );
}
return ( $sym, length( pack "a*", $re ) );
}
sub constpv {
my $pv = pack "a*", shift;
if (exists $strtable{$pv}) {
return $strtable{$pv};
}
my $pvsym = sprintf( "pv%d", $pv_index++ );
$strtable{$pv} = "$pvsym";
my $const = ($B::C::pv_copy_on_grow and $B::C::const_strings) ? " const" : "";
if ( defined $max_string_len && length($pv) > $max_string_len ) {
my $chars = join ', ', map { cchar $_ } split //, $pv;
$decl->add( sprintf( "Static$const char %s[] = { %s };", $pvsym, $chars ) );
} else {
my $cstring = cstring($pv);
if ( $cstring ne "0" ) { # sic
$decl->add( sprintf( "Static$const char %s[] = %s;", $pvsym, $cstring ) );
}
}
return wantarray ? ( $pvsym, length( pack "a*", $pv ) ) : $pvsym;
}
sub savepv {
return constpv($_[0]) if $B::C::const_strings and $B::C::pv_copy_on_grow; # or readonly
my $pv = pack "a*", shift;
my $pvsym = sprintf( "pv%d", $pv_index++ );
if ( defined $max_string_len && length($pv) > $max_string_len ) {
my $chars = join ', ', map { cchar $_ } split //, $pv;
$decl->add( sprintf( "Static char %s[] = { %s };", $pvsym, $chars ) );
} else {
my $cstring = cstring($pv);
if ( $cstring ne "0" ) { # sic
$decl->add( sprintf( "Static char %s[] = %s;", $pvsym, $cstring ) );
}
}
my $len = length( pack "a*", $pv ) + 1;
return ( $pvsym, $len );
}
sub save_rv {
my ($sv, $fullname) = @_;
if (!$fullname) {
$fullname = '(unknown)';
}
# confess "Can't save RV: not ROK" unless $sv->FLAGS & SVf_ROK;
# 5.6: Can't locate object method "RV" via package "B::PVMG"
my $rv = $sv->RV->save($fullname);
$rv =~ s/^\(([AGHS]V|IO)\s*\*\)\s*(\&sv_list.*)$/$2/;
return $rv;
}
# => savesym, cur, len, pv
sub save_pv_or_rv {
my ($sv, $fullname) = @_;
my $rok = $sv->FLAGS & SVf_ROK;
my $pok = $sv->FLAGS & SVf_POK;
my ( $cur, $len, $savesym, $pv ) = ( 0, 0 );
# overloaded VERSION symbols fail to xs boot: ExtUtils::CBuilder with Fcntl::VERSION (i91)
# 5.6: Can't locate object method "RV" via package "B::PV" Carp::Clan
if ($rok and !$PERL56) {
# this returns us a SV*. 5.8 expects a char* in xpvmg.xpv_pv
warn "save_pv_or_rv: save_rv(",$sv,")\n" if $debug{sv};
$savesym = ($PERL510 ? "" : "(char*)") . save_rv($sv, $fullname);
}
else {
$pv = $pok ? ( pack "a*", $sv->PV ) : undef;
$cur = $pok ? length($pv) : 0;
my $shared_hek = $PERL510 ? (($sv->FLAGS & 0x09000000) == 0x09000000) : undef;
local $B::C::pv_copy_on_grow if $shared_hek;
if ($pok) {
if ($B::C::pv_copy_on_grow) {
( $savesym, $len ) = ($B::C::const_strings and $sv->FLAGS & SVf_READONLY)
? constpv($pv) : savepv($pv);
} else {
( $savesym, $len ) = ( 'ptr_undef', $cur+1 );
}
} else {
( $savesym, $len ) = ( 'ptr_undef', 0 );
}
}
return ( $savesym, $cur, $len, $pv );
}
# Shared global string in PL_strtab.
# Mostly GvNAME and GvFILE, but also CV prototypes or bareword hash keys.
sub save_hek {
my $str = shift; # not cstring'ed
my $len = length $str;
# force empty string for CV prototypes
if (!$len and !@_) { wantarray ? return ( "NULL", 0 ) : return "NULL"; }
if (exists $hektable{$str}) {
return wantarray ? ($hektable{$str}, length( pack "a*", $hektable{$str} ))
: $hektable{$str};
}
my $cur = length( pack "a*", $str );
my $sym = sprintf( "hek%d", $hek_index++ );
$hektable{$str} = $sym;
my $cstr = cstring($str);
$decl->add(sprintf("Static HEK *%s;",$sym));
# randomized global shared hash keys:
# share_hek needs a non-zero hash parameter, unlike hv_store.
# Vulnerable to oCERT-2011-003 style DOS attacks?
# user-input (object fields) does not affect strtab, it is pretty safe.
# But we need to randomize them to avoid run-time conflicts
# e.g. "Prototype mismatch: sub bytes::length (_) vs (_)"
$init->add(sprintf("%s = share_hek(%s, %u, %s);",
$sym, $cstr, $cur, '0'));
wantarray ? ( $sym, $cur ) : $sym;
}
sub ivx ($) {
my $ivx = shift;
my $ivdformat = $Config{ivdformat};
$ivdformat =~ s/"//g; #" poor editor
my $intmax = (1 << ($Config{ivsize}*4-1)) - 1;
# LL if INT32_MAX .. INT64_MAX
# UL if > INT32_MAX = 2147483647
my $ll = $Config{d_longlong} ? "LL" : "UL";
my $sval = sprintf("%${ivdformat}%s", $ivx, $ivx > $intmax ? $ll : "");
if ($ivx < -$intmax) {
my $l = $Config{d_longlong} ? "LL" : "L";
$sval = sprintf("%${ivdformat}%s", $ivx, $l); # DateTime
}
$sval = '0' if $sval =~ /(NAN|inf)$/i;
return $sval;
#return $C99 ? ".xivu_uv = $sval" : $sval; # this is version dependent
}
# protect from warning: floating constant exceeds range of ‘double’ [-Woverflow]
sub nvx ($) {
my $nvx = shift;
my $nvgformat = $Config{nvgformat};
$nvgformat =~ s/"//g; #" poor editor
my $dblmax = "1.79769313486232e+308";
# my $ldblmax = "1.18973149535723176502e+4932L"
my $ll = $Config{d_longdbl} ? "LL" : "L";
if ($nvgformat eq 'g') { # a very poor choice to keep precision
# on intel 17-18, on ppc 31, on sparc64/s390 34
$nvgformat = $Config{uselongdouble} ? '.17Lg' : '.16g';
}
my $sval = sprintf("%${nvgformat}%s", $nvx, $nvx > $dblmax ? $ll : "");
if ($nvx < -$dblmax) {
$sval = sprintf("%${nvgformat}%s", $nvx, $ll);
}
$sval = '0' if $sval =~ /(NAN|inf)$/i;
$sval .= '.00' if $sval =~ /^-?\d+$/;
return $sval;
}
# See also init_op_ppaddr below; initializes the ppaddr to the
# OpTYPE; init_op_ppaddr iterates over the ops and sets
# op_ppaddr to PL_ppaddr[op_ppaddr]; this avoids an explicit assignment
# in perl_init ( ~10 bytes/op with GCC/i386 )
sub B::OP::fake_ppaddr {
return "NULL" unless $_[0]->can('name');
return $B::C::optimize_ppaddr
? sprintf( "INT2PTR(void*,OP_%s)", uc( $_[0]->name ) )
: ( $verbose ? sprintf( "/*OP_%s*/NULL", uc( $_[0]->name ) ) : "NULL" );
}
sub B::FAKEOP::fake_ppaddr { "NULL" }
# XXX HACK! duct-taping around compiler problems
sub B::OP::isa { UNIVERSAL::isa(@_) } # walkoptree_slow misses that
sub B::OP::can { UNIVERSAL::can(@_) }
sub B::OBJECT::name { "" } # B misses that
$isa_cache{'B::OBJECT::can'} = 'UNIVERSAL';
# This pair is needed because B::FAKEOP::save doesn't scalar dereference
# $op->next and $op->sibling
my $opsect_common =
"next, sibling, ppaddr, " . ( $MAD ? "madprop, " : "" ) . "targ, type, ";
{
# For 5.8:
# Current workaround/fix for op_free() trying to free statically
# defined OPs is to set op_seq = -1 and check for that in op_free().
# Instead of hardwiring -1 in place of $op->seq, we use $op_seq
# so that it can be changed back easily if necessary. In fact, to
# stop compilers from moaning about a U16 being initialised with an
# uncast -1 (the printf format is %d so we can't tweak it), we have
# to "know" that op_seq is a U16 and use 65535. Ugh.
# For 5.9 the hard coded text is the values for op_opt and op_static in each
# op. The value of op_opt is irrelevant, and the value of op_static needs to
# be 1 to tell op_free that this is a statically defined op and that is
# shouldn't be freed.
# For 5.10 op_seq = -1 is gone, the temp. op_static also, but we
# have something better, we can set op_latefree to 1, which frees the children
# (e.g. savepvn), but not the static op.
# 5.8: U16 op_seq;
# 5.9.4: unsigned op_opt:1; unsigned op_static:1; unsigned op_spare:5;
# 5.10: unsigned op_opt:1; unsigned op_latefree:1; unsigned op_latefreed:1; unsigned op_attached:1; unsigned op_spare:3;
my $static;
if ( $] < 5.009004 ) {
$static = sprintf "%u", 65535;
$opsect_common .= "seq";
}
elsif ( $] < 5.010 ) {
$static = '0, 1, 0';
$opsect_common .= "opt, static, spare";
}
elsif ($] < 5.017002) {
$static = '0, 1, 0, 0, 0';
$opsect_common .= "opt, latefree, latefreed, attached, spare";
}
elsif ($] < 5.017004) {
$static = '0, 1, 0, 0, 0, 0, 0';
$opsect_common .= "opt, latefree, latefreed, attached, slabbed, savefree, spare";
}
elsif ($] < 5.017006) {
$static = '0, 1, 0, 0, 0, 0, 0';
$opsect_common .= "opt, latefree, latefreed, attached, slabbed, savefree, spare";
}
else { # 90840c5d1d 5.17.6
$static = '0, 0, 0, 1, 0';
$opsect_common .= "opt, slabbed, savefree, static, spare";
}
sub B::OP::_save_common_middle {
my $op = shift;
my $madprop = $MAD ? "0," : "";
# XXX maybe add a ix=opindex string for debugging if $debug{flags}
sprintf( "%s,%s %u, %u, $static, 0x%x, 0x%x",
$op->fake_ppaddr, $madprop, $op->targ, $op->type, $op->flags, $op->private );
}
$opsect_common .= ", flags, private";
}
# run-time loaded package, detected via bless or new.
sub force_dynpackage {
my $pv = shift;
no strict 'refs';
if ($pv and !$skip_package{$pv} and $pv !~ /^B::/) { # XXX only loaded at run-time
if (!$INC{inc_packname($pv)}) {
eval "require $pv;";
if (!$@) {
if (!$INC{inc_packname($pv)}) {
warn "Warning: Problem with require \"$pv\" - !\$INC{".inc_packname($pv)."}\n";
} else {
warn "load \"$pv\"\n" if $debug{meth};
}
}
}
mark_package($pv);
}
}
# Heuristic to check method calls for the class to store the full sub name.
# Also associate objects with classes - $obj=new Class; - to resolve method calls later.
# Compile-time method_named packages are always const PV sM/BARE.
# run-time packages ("objects") are in padsv (printed as gvsv).
# my Foo $obj = shift; $obj->bar();
# entersub -> pushmark -> package -> args.. -> method_named|method
# See perl -MO=Terse -e '$foo->bar("var")'
# See also http://www.perl.com/pub/2000/06/dougpatch.html
sub check_entersub {
my $op = shift;
my $cv = shift;
$cv = $B::C::curcv unless $cv;
if ($op->type > 0 and
$op->name eq 'entersub' and $op->first and $op->first->can('name') and
$op->first->name eq 'pushmark' and
# Foo->bar() compile-time lookup, 34 WANT_SCALAR,MOD in all versions
(($op->first->next->name eq 'const' and $op->first->next->flags == 34)
# or $foo->bar() run-time lookup
or ($op->first->next->name eq 'padsv'))) # note that padsv is called gvsv in Concise
{
my $pkgop = $op->first->next; # padsv for objects or const for classes
my $methop = $pkgop; # walk args until method or sub end. This ends
do { $methop = $methop->next; }
while ($methop->name !~ /^method_named|method$/
or ($methop->name eq 'gv' and $methop->next->name ne 'entersub'));
my $methopname = $methop->name;
if (substr($methopname,0,6) eq 'method') {
my $methodname = $methopname eq 'method' ? svop_name($methop, $cv) : svop_pv($methop, $cv);
if ($pkgop->name eq 'const') {
my $pv = svop_pv($pkgop, $cv); # 5.13: need to store away the pkg pv
if ($pv and $pv !~ /[! \(]/) {
warn "check package_pv $pv for $methopname \"$methodname\"\n" if $debug{meth};
# padsv package names are dynamic. They cannot be determined at compile-time,
# unless they are typed.
# We can catch the 'new' method and assign the const package_pv to the symbol
# and compare the padsv then. $foo=new Class;$foo->method; #main::foo => Class
# Note: 'new' is no keyword (yet), but good enough. We check bless also.
if ($methopname eq 'method_named' and 'new' eq svop_pv($methop, $cv)) {
my $objname = svop_name($pkgop);
my $symop = $op->next;
if (($symop->name eq 'padsv' or $symop->name eq 'gvsv')
and $symop->next->name eq 'sassign') {
no strict 'refs';
warn "cache object $objname = new $pv;\n" if $debug{meth};
force_dynpackage($pv);
svref_2object( \&{"$pv\::$methodname"} )->save
if $methodname and defined(&{"$pv\::$methodname"});
cache_svop_pkg($symop, $pv);
}
}
$package_pv = $pv;
push_package($package_pv);
}
} elsif ($pkgop->name eq 'padsv') { # check cached obj class
my $objname = padop_name($pkgop, $cv) || '';
if (my $pv = cache_svop_pkg($pkgop)) {
warn "cached package for $objname->$methodname found: \"$pv\"\n" if $debug{meth};
svref_2object( \&{"$pv\::$methodname"} )->save
if $methodname and defined(&{"$pv\::$methodname"});
$package_pv = $pv;