xref: /openbsd/gnu/usr.bin/perl/ext/B/t/b.t (revision 6f40fd34)
1#!./perl
2
3BEGIN {
4    unshift @INC, 't';
5    require Config;
6    if (($Config::Config{'extensions'} !~ /\bB\b/) ){
7        print "1..0 # Skip -- Perl configured without B module\n";
8        exit 0;
9    }
10}
11
12$|  = 1;
13use warnings;
14use strict;
15BEGIN  {
16    eval { require threads; threads->import; }
17}
18use Test::More;
19
20BEGIN { use_ok( 'B' ); }
21
22
23package Testing::Symtable;
24use vars qw($This @That %wibble $moo %moo);
25my $not_a_sym = 'moo';
26
27sub moo { 42 }
28sub car { 23 }
29
30
31package Testing::Symtable::Foo;
32sub yarrow { "Hock" }
33
34package Testing::Symtable::Bar;
35sub hock { "yarrow" }
36
37package main;
38use vars qw(%Subs);
39local %Subs = ();
40B::walksymtable(\%Testing::Symtable::, 'find_syms', sub { $_[0] =~ /Foo/ },
41                'Testing::Symtable::');
42
43sub B::GV::find_syms {
44    my($symbol) = @_;
45
46    $main::Subs{$symbol->STASH->NAME . '::' . $symbol->NAME}++;
47}
48
49my @syms = map { 'Testing::Symtable::'.$_ } qw(This That wibble moo car
50                                               BEGIN);
51push @syms, "Testing::Symtable::Foo::yarrow";
52
53# Make sure we hit all the expected symbols.
54ok( join('', sort @syms) eq join('', sort keys %Subs), 'all symbols found' );
55
56# Make sure we only hit them each once.
57ok( (!grep $_ != 1, values %Subs), '...and found once' );
58
59# Tests for MAGIC / MOREMAGIC
60ok( B::svref_2object(\$.)->MAGIC->TYPE eq "\0", '$. has \0 magic' );
61{
62    my $e = '';
63    local $SIG{__DIE__} = sub { $e = $_[0] };
64    # Used to dump core, bug #16828
65    eval { B::svref_2object(\$.)->MAGIC->MOREMAGIC->TYPE; };
66    like( $e, qr/Can't call method "TYPE" on an undefined value/,
67	'$. has no more magic' );
68}
69
70{
71    my $pie = 'Good';
72    # This needs to be a package variable, as vars in the pad have some flags.
73    my $r = B::svref_2object(\$::data2);
74    is($r->FLAGS(), 0, "uninitialised package variable has flags of 0");
75    is($r->SvTYPE(), 0, "uninitialised package variable has type 0");
76    is($r->POK(), 0, "POK false");
77    is($r->ROK(), 0, "ROK false");
78    is($r->MAGICAL(), 0, "MAGICAL false");
79    $::data2 = $pie;
80    isnt($r->FLAGS(), 0, "initialised package variable has nonzero flags");
81    isnt($r->SvTYPE(), 0, "initialised package variable has nonzero type");
82    isnt($r->POK(), 0, "POK true");
83    is($r->ROK(), 0, "ROK false");
84    is($r->MAGICAL(), 0, "MAGICAL false");
85
86    $::data2 = substr $pie, 0, 1;
87    isnt($r->FLAGS(), 0, "initialised package variable has nonzero flags");
88    isnt($r->SvTYPE(), 0, "initialised package variable has nonzero type");
89    isnt($r->POK(), 0, "POK true");
90    is($r->ROK(), 0, "ROK false");
91    is($r->MAGICAL(), 0, "MAGICAL true");
92
93    $::data2 = \$pie;
94    isnt($r->FLAGS(), 0, "initialised package variable has nonzero flags");
95    isnt($r->SvTYPE(), 0, "initialised package variable has nonzero type");
96    is($r->POK(), 0, "POK false");
97    isnt($r->ROK(), 0, "ROK true");
98    is($r->MAGICAL(), 0, "MAGICAL false");
99
100    is($r->REFCNT(), 1, "Reference count is 1");
101    {
102	my $ref = \$::data2;
103	is($r->REFCNT(), 2, "Second reference");
104    }
105    is($r->REFCNT(), 1, "Reference count is 1");
106
107}
108
109my $r = qr/foo/;
110my $obj = B::svref_2object($r);
111my $regexp =  ($] < 5.011) ? $obj->MAGIC : $obj;
112ok($regexp->precomp() eq 'foo', 'Get string from qr//');
113like($regexp->REGEX(), qr/\d+/, "REGEX() returns numeric value");
114like($regexp->compflags, qr/^\d+\z/, "compflags returns numeric value");
115is B::svref_2object(qr/(?{time})/)->qr_anoncv->ROOT->first->name, 'qr',
116  'qr_anoncv';
117my $iv = 1;
118my $iv_ref = B::svref_2object(\$iv);
119is(ref $iv_ref, "B::IV", "Test B:IV return from svref_2object");
120is($iv_ref->REFCNT, 1, "Test B::IV->REFCNT");
121# Flag tests are needed still
122#diag $iv_ref->FLAGS();
123my $iv_ret = $iv_ref->object_2svref();
124is(ref $iv_ret, "SCALAR", "Test object_2svref() return is SCALAR");
125is($$iv_ret, $iv, "Test object_2svref()");
126is($iv_ref->int_value, $iv, "Test int_value()");
127is($iv_ref->IV, $iv, "Test IV()");
128is($iv_ref->IVX(), $iv, "Test IVX()");
129is($iv_ref->UVX(), $iv, "Test UVX()");
130is(eval { $iv_ref->RV() }, undef, 'Test RV() on IV');
131like($@, qr/argument is not SvROK/, 'Test RV() IV');
132$iv = \"Pie";
133my $val = eval { $iv_ref->RV() };
134is(ref $val, 'B::PV', 'Test RV() on a reference');
135is($val->PV(), 'Pie', 'Value expected');
136is($@, '', "Test RV()");
137
138my $pv = "Foo";
139my $pv_ref = B::svref_2object(\$pv);
140is(ref $pv_ref, "B::PV", "Test B::PV return from svref_2object");
141is($pv_ref->REFCNT, 1, "Test B::PV->REFCNT");
142# Flag tests are needed still
143#diag $pv_ref->FLAGS();
144my $pv_ret = $pv_ref->object_2svref();
145is(ref $pv_ret, "SCALAR", "Test object_2svref() return is SCALAR");
146is($$pv_ret, $pv, "Test object_2svref()");
147is($pv_ref->PV(), $pv, "Test PV()");
148is(eval { $pv_ref->RV() }, undef, 'Test RV() on PV');
149like($@, qr/argument is not SvROK/, 'Test RV() on PV');
150is($pv_ref->PVX(), $pv, "Test PVX()");
151$pv = \"Pie";
152$val = eval { $pv_ref->RV() };
153is(ref $val, 'B::PV', 'Test RV() on a reference');
154is($val->PV(), 'Pie', 'Value expected');
155is($@, '', "Test RV()");
156
157my $nv = 1.1;
158my $nv_ref = B::svref_2object(\$nv);
159is(ref $nv_ref, "B::NV", "Test B::NV return from svref_2object");
160is($nv_ref->REFCNT, 1, "Test B::NV->REFCNT");
161# Flag tests are needed still
162#diag $nv_ref->FLAGS();
163my $nv_ret = $nv_ref->object_2svref();
164is(ref $nv_ret, "SCALAR", "Test object_2svref() return is SCALAR");
165is($$nv_ret, $nv, "Test object_2svref()");
166is($nv_ref->NV, $nv, "Test NV()");
167is($nv_ref->NVX(), $nv, "Test NVX()");
168is(eval { $nv_ref->RV() }, undef, 'Test RV() on NV');
169like($@, qr/Can't locate object method "RV" via package "B::NV"/,
170     'Test RV() on NV');
171
172my $null = undef;
173my $null_ref = B::svref_2object(\$null);
174is(ref $null_ref, "B::NULL", "Test B::NULL return from svref_2object");
175is($null_ref->REFCNT, 1, "Test B::NULL->REFCNT");
176# Flag tests are needed still
177#diag $null_ref->FLAGS();
178my $null_ret = $nv_ref->object_2svref();
179is(ref $null_ret, "SCALAR", "Test object_2svref() return is SCALAR");
180is($$null_ret, $nv, "Test object_2svref()");
181
182my $RV_class = $] >= 5.011 ? 'B::IV' : 'B::RV';
183my $cv = sub{ 1; };
184my $cv_ref = B::svref_2object(\$cv);
185is($cv_ref->REFCNT, 1, "Test $RV_class->REFCNT");
186is(ref $cv_ref, "$RV_class",
187   "Test $RV_class return from svref_2object - code");
188my $cv_ret = $cv_ref->object_2svref();
189is(ref $cv_ret, "REF", "Test object_2svref() return is REF");
190is($$cv_ret, $cv, "Test object_2svref()");
191
192my $av = [];
193my $av_ref = B::svref_2object(\$av);
194is(ref $av_ref, "$RV_class",
195   "Test $RV_class return from svref_2object - array");
196
197my $hv = [];
198my $hv_ref = B::svref_2object(\$hv);
199is(ref $hv_ref, "$RV_class",
200   "Test $RV_class return from svref_2object - hash");
201
202local *gv = *STDOUT;
203my $gv_ref = B::svref_2object(\*gv);
204is(ref $gv_ref, "B::GV", "Test B::GV return from svref_2object");
205ok(! $gv_ref->is_empty(), "Test is_empty()");
206ok($gv_ref->isGV_with_GP(), "Test isGV_with_GP()");
207is($gv_ref->NAME(), "gv", "Test NAME()");
208is($gv_ref->SAFENAME(), "gv", "Test SAFENAME()");
209like($gv_ref->FILE(), qr/b\.t$/, "Testing FILE()");
210is($gv_ref->SvTYPE(), B::SVt_PVGV, "Test SvTYPE()");
211is($gv_ref->FLAGS() & B::SVTYPEMASK, B::SVt_PVGV, "Test SVTYPEMASK");
212
213# The following return B::SPECIALs.
214is(ref B::sv_yes(), "B::SPECIAL", "B::sv_yes()");
215is(ref B::sv_no(), "B::SPECIAL", "B::sv_no()");
216is(ref B::sv_undef(), "B::SPECIAL", "B::sv_undef()");
217SKIP: {
218    skip('no fork', 1)
219	unless ($Config::Config{d_fork} or $Config::Config{d_pseudofork});
220    my $pid;
221    pipe my $r, my $w or die "Can't pipe: $!";;
222    if ($pid = fork) {
223        close $w;
224        my $type = <$r>;
225        close $r;
226        waitpid($pid,0);
227        is($type, "B::SPECIAL", "special SV table works after pseudofork");
228    }
229    else {
230        close $r;
231        $|++;
232        print $w ref B::svref_2object(\(!!0));
233        close $w;
234        exit;
235    }
236}
237
238# More utility functions
239is(B::ppname(0), "pp_null", "Testing ppname (this might break if opnames.h is changed)");
240is(B::opnumber("null"), 0, "Testing opnumber with opname (null)");
241is(B::opnumber("pp_null"), 0, "Testing opnumber with opname (pp_null)");
242{
243    my $hash = B::hash("wibble");
244    like($hash, qr/\A0x[0-9a-f]+\z/, "Testing B::hash(\"wibble\")");
245    unlike($hash, qr/\A0x0+\z/, "Testing B::hash(\"wibble\")");
246
247    SKIP: {
248        skip "Nulls don't hash to the same bucket regardless of length with this PERL_HASH implementation", 20
249            if B::hash("") ne B::hash("\0" x 19);
250        like(B::hash("\0" x $_), qr/\A0x0+\z/, "Testing B::hash(\"0\" x $_)")
251             for 0..19;
252    }
253
254    $hash = eval {B::hash(chr 256)};
255    is($hash, undef, "B::hash() refuses non-octets");
256    like($@, qr/^Wide character in subroutine entry/);
257
258    $hash = B::hash(chr 163);
259    my $str = chr(163) . chr 256;
260    chop $str;
261    is(B::hash($str), $hash, 'B::hash() with chr 128-256 is well-behaved');
262}
263{
264    is(B::cstring(undef), '0', "Testing B::cstring(undef)");
265    is(B::perlstring(undef), '0', "Testing B::perlstring(undef)");
266
267    my @common = map {eval $_, $_}
268	'"wibble"', '"\""', '"\'"', '"\\\\"', '"\\n\\r\\t\\b\\a\\f"', '"\000"',
269	    '"\000\000"', '"\000Bing\000"', ord 'N' == 78 ? '"\\177"' : ();
270
271    my $oct = sprintf "\\%03o", ord '?';
272    my @tests = (@common, '$_', '"$_"', '@_', '"@_"', '??N', qq{"$oct?N"},
273		 ord 'N' == 78 ? (chr 11, '"\v"'): ());
274    while (my ($test, $expect) = splice @tests, 0, 2) {
275	is(B::cstring($test), $expect, "B::cstring($expect)");
276    }
277
278    @tests = (@common, '$_', '"\$_"', '@_', '"\@_"', '??N', '"??N"',
279	      chr 256, '"\x{100}"', chr 65536, '"\x{10000}"',
280	      ord 'N' == 78 ? (chr 11, '"\013"'): ());
281    while (my ($test, $expect) = splice @tests, 0, 2) {
282	is(B::perlstring($test), $expect, "B::perlstring($expect)");
283	utf8::upgrade $test;
284	$expect =~ s/\\b/sprintf("\\x{%x}", utf8::unicode_to_native(8))/eg;
285	$expect =~ s/\\([0-7]{3})/sprintf "\\x\{%x\}", oct $1/eg;
286	is(B::perlstring($test), $expect, "B::perlstring($expect) (Unicode)");
287    }
288}
289{
290    my @tests = ((map {eval(qq{"$_"}), $_} '\\n', '\\r', '\\t',
291		  '\\b', '\\a', '\\f', '\\000', '\\\'', '?'), '"', '"',
292		 ord 'N' == 78 ? (chr 11, '\v', "\177", '\\177') : ());
293
294    while (my ($test, $expect) = splice @tests, 0, 2) {
295	is(B::cchar($test), "'${expect}'", "B::cchar(qq{$expect})");
296    }
297}
298
299is(B::class(bless {}, "Wibble::Bibble"), "Bibble", "Testing B::class()");
300is(B::cast_I32(3.14), 3, "Testing B::cast_I32()");
301is(B::opnumber("chop"), $] >= 5.015 ? 39 : 38,
302			    "Testing opnumber with opname (chop)");
303
304{
305    no warnings 'once';
306    my $sg = B::sub_generation();
307    *UNIVERSAL::hand_waving = sub { };
308    ok( $sg < B::sub_generation, "sub_generation increments" );
309}
310
311like( B::amagic_generation, qr/^\d+\z/, "amagic_generation" );
312
313is(B::svref_2object(sub {})->ROOT->ppaddr, 'PL_ppaddr[OP_LEAVESUB]',
314   'OP->ppaddr');
315
316# This one crashes from perl 5.8.9 to B 1.24 (perl 5.13.6):
317B::svref_2object(sub{y/\x{100}//})->ROOT->first->first->sibling->sv;
318ok 1, 'B knows that UTF trans is a padop in 5.8.9, not an svop';
319
320{
321    my $o = B::svref_2object(sub{0;0})->ROOT->first->first;
322    # Make sure we are testing what we think we are testing.  If these two
323    # fail, tweak the test to find a nulled cop a different way.
324    is $o->name, "null", 'first op of sub{0;0} is a null';
325    is B::ppname($o->targ),'pp_nextstate','first op of sub{0;0} was a cop';
326    # Test its class
327    is B::class($o), "COP", 'nulled cops are of class COP';
328}
329
330{
331    format FOO =
332foo
333.
334    my $f = B::svref_2object(*FOO{FORMAT});
335    isa_ok $f, 'B::FM';
336    can_ok $f, 'LINES';
337}
338
339is B::safename("\cLAST_FH"), "^LAST_FH", 'basic safename test';
340
341my $sub1 = sub {die};
342{ no warnings 'once'; no strict; *Peel:: = *{"Pe\0e\x{142}::"} }
343my $sub2 = eval 'package Peel; sub {die}';
344my $cop = B::svref_2object($sub1)->ROOT->first->first;
345my $bobby = B::svref_2object($sub2)->ROOT->first->first;
346is $cop->stash->object_2svref, \%main::, 'COP->stash';
347is $cop->stashpv, 'main', 'COP->stashpv';
348
349SKIP: {
350    skip "no nulls in packages before 5.17", 1 if $] < 5.017;
351    is $bobby->stashpv, "Pe\0e\x{142}", 'COP->stashpv with utf8 and nulls';
352}
353
354SKIP: {
355    skip "no stashoff", 2 if $] < 5.017 || !$Config::Config{useithreads};
356    like $cop->stashoff, qr/^[1-9]\d*\z/a, 'COP->stashoff';
357    isnt $cop->stashoff, $bobby->stashoff,
358	'different COP->stashoff for different stashes';
359}
360
361my $pmop = B::svref_2object(sub{ qr/fit/ })->ROOT->first->first->sibling;
362$regexp = $pmop->pmregexp;
363is B::class($regexp), 'REGEXP', 'B::PMOP::pmregexp returns a regexp';
364is $regexp->precomp, 'fit', 'pmregexp returns the right regexp';
365
366
367# Test $B::overlay
368{
369    my $methods = {
370	BINOP =>  [ qw(last) ],
371	COP   =>  [ qw(arybase cop_seq file filegv hints hints_hash io
372		       label line stash stashpv
373		       stashoff warnings) ],
374	LISTOP => [ qw(children) ],
375	LOGOP =>  [ qw(other) ],
376	LOOP  =>  [ qw(lastop nextop redoop) ],
377	OP    =>  [ qw(desc flags name next opt ppaddr private sibling
378		       size spare targ type) ],
379	PADOP =>  [ qw(gv padix sv) ],
380	PMOP  =>  [ qw(code_list pmflags pmoffset pmreplroot pmreplstart pmstash pmstashpv precomp reflags) ],
381	PVOP  =>  [ qw(pv) ],
382	SVOP  =>  [ qw(gv sv) ],
383	UNOP  =>  [ qw(first) ],
384    };
385
386    my $overlay = {};
387    my $op = B::svref_2object(sub { my $x = 1 })->ROOT;
388
389    for my $class (sort keys %$methods) {
390	for my $meth (@{$methods->{$class}}) {
391	    my $full = "B::${class}::$meth";
392	    die "Duplicate method '$full'\n"
393		if grep $_ eq $full, @{$overlay->{$meth}};
394	    push @{$overlay->{$meth}}, "B::${class}::$meth";
395	}
396    }
397
398    {
399	local $B::overlay; # suppress 'used once' warning
400	local $B::overlay = { $$op => $overlay };
401
402	for my $class (sort keys %$methods) {
403	    bless $op, "B::$class"; # naughty
404	    for my $meth (@{$methods->{$class}}) {
405		if ($op->can($meth)) {
406		    my $list = $op->$meth;
407		    ok(defined $list
408			    && ref($list) eq "ARRAY"
409			    && grep($_ eq "B::${class}::$meth", @$list),
410			"overlay: B::$class $meth");
411		}
412		else {
413		    pass("overlay: B::$class $meth (skipped; no method)");
414		}
415	    }
416	}
417    }
418    # B::overlay should be disabled again here
419    is($op->name, "leavesub", "overlay: orig name");
420}
421
422{ # [perl #118525]
423    {
424        sub foo {}
425	my $cv = B::svref_2object(\&foo);
426	ok($cv, "make a B::CV from a non-anon sub reference");
427	isa_ok($cv, "B::CV");
428	my $gv = $cv->GV;
429	ok($gv, "we get a GV from a GV on a normal sub");
430	isa_ok($gv, "B::GV");
431	is($gv->NAME, "foo", "check the GV name");
432      SKIP:
433	{ # do we need these version checks?
434	    skip "no HEK before 5.18", 1 if $] < 5.018;
435	    is($cv->NAME_HEK, undef, "no hek for a global sub");
436	}
437    }
438
439SKIP:
440    {
441        skip "no HEK before 5.18", 4 if $] < 5.018;
442        eval <<'EOS'
443    {
444        use feature 'lexical_subs';
445        no warnings 'experimental::lexical_subs';
446        my sub bar {};
447        my $cv = B::svref_2object(\&bar);
448        ok($cv, "make a B::CV from a lexical sub reference");
449        isa_ok($cv, "B::CV");
450        my $hek = $cv->NAME_HEK;
451        is($hek, "bar", "check the NAME_HEK");
452        my $gv = $cv->GV;
453        isa_ok($gv, "B::GV", "GV on a lexical sub");
454    }
455    1;
456EOS
457	  or die "lexical_subs test failed to compile: $@";
458    }
459}
460
461{ # [perl #120535]
462    my %h = ( "\x{100}" => 1 );
463    my $b = B::svref_2object(\%h);
464    my ($k, $v) = $b->ARRAY;
465    is($k, "\x{100}", "check utf8 preserved by B::HV::ARRAY");
466}
467
468# test op_parent
469
470SKIP: {
471    unless ($B::OP::does_parent) {
472        skip "op_parent only present with -DPERL_OP_PARENT builds", 6;
473    }
474    my $lineseq = B::svref_2object(sub{my $x = 1})->ROOT->first;
475    is ($lineseq->type,  B::opnumber('lineseq'),
476                                'op_parent: top op is lineseq');
477    my $first  = $lineseq->first;
478    my $second = $first->sibling;
479    is(ref $second->sibling, "B::NULL", 'op_parent: second sibling is null');
480    is($first->moresib,  1 , 'op_parent: first  sibling: moresib');
481    is($second->moresib, 0,  'op_parent: second sibling: !moresib');
482    is($$lineseq,  ${$first->parent},   'op_parent: first  sibling okay');
483    is($$lineseq,  ${$second->parent},  'op_parent: second sibling okay');
484}
485
486
487# make sure ->sv, -gv methods do the right thing on threaded builds
488{
489
490    # for some reason B::walkoptree only likes a sub name, not a code ref
491    my ($gv, $sv);
492    sub gvsv_const {
493        # make the early pad slots something unlike a threaded const or
494        # gvsv
495        my ($dummy1, $dummy2, $dummy3, $dummy4) = qw(foo1 foo2 foo3 foo4);
496        my $self = shift;
497        if ($self->name eq 'gvsv') {
498            $gv = $self->gv;
499        }
500        elsif ($self->name eq 'const') {
501            $sv = $self->sv;
502        }
503    };
504
505    B::walkoptree(B::svref_2object(sub {our $x = 1})->ROOT, "::gvsv_const");
506    ok(defined $gv, "gvsv->gv seen");
507    ok(defined $sv, "const->sv seen");
508    if ($Config::Config{useithreads}) {
509        # should get NULLs
510        is(ref($gv), "B::SPECIAL", "gvsv->gv is special");
511        is(ref($sv), "B::SPECIAL", "const->sv is special");
512        is($$gv, 0, "gvsv->gv special is 0 (NULL)");
513        is($$sv, 0, "const->sv special is 0 (NULL)");
514    }
515    else {
516        is(ref($gv), "B::GV", "gvsv->gv is GV");
517        is(ref($sv), "B::IV", "const->sv is IV");
518        pass();
519        pass();
520    }
521
522}
523
524
525# Some pad tests
526{
527    my $sub = sub { my main $a; CORE::state @b; our %c };
528    my $padlist = B::svref_2object($sub)->PADLIST;
529    is $padlist->MAX, 1, 'padlist MAX';
530    my @array = $padlist->ARRAY;
531    is @array, 2, 'two items from padlist ARRAY';
532    is ${$padlist->ARRAYelt(0)}, ${$array[0]},
533      'ARRAYelt(0) is first item from ARRAY';
534    is ${$padlist->ARRAYelt(1)}, ${$array[1]},
535      'ARRAYelt(1) is second item from ARRAY';
536    is ${$padlist->NAMES}, ${$array[0]},
537      'NAMES is first item from ARRAY';
538    my @names = $array[0]->ARRAY;
539    cmp_ok @names, ">=", 4, 'at least 4 pad names';
540    is join(" ", map($_->PV//"undef",@names[0..3])), 'undef $a @b %c',
541       'pad name PVs';
542
543    my @closures;
544    for (1,2) { push @closures, sub { sub { @closures } } }
545    my $sub1 = B::svref_2object($closures[0]);
546    my $sub2 = B::svref_2object($closures[1]);
547    is $sub2->PADLIST->id, $sub1->PADLIST->id, 'padlist id';
548    $sub1 = B::svref_2object(my $lr = $closures[0]());
549    $sub2 = B::svref_2object(my $lr2= $closures[1]());
550    is $sub2->PADLIST->outid, $sub1->PADLIST->outid, 'padlist outid';
551}
552
553
554done_testing();
555