Assertion failure with $/=*foo; warn;

$ ./perl -Ilib -e '$/=*foo; <>; warn' <./perl
Assertion failed: (!isGV_with_GP(_svcur)), function Perl_mess_sv, file util.c, line 1467.
Abort trap

The assertion happens when ‘<...> line 42’ is being appended to
the message.

The line of code in question is this:

	    const bool line_mode = (RsSIMPLE(PL_rs) &&
			      SvCUR(PL_rs) == 1 && *SvPVX_const(PL_rs) == '\n');

It uses this macro in perl.h:

#define RsSIMPLE(sv)  (SvOK(sv) && (! SvPOK(sv) || SvCUR(sv)))

which was last modified by commit af7d13df559:

-#define RsSIMPLE(sv)  (SvOK(sv) && SvCUR(sv))
-#define RsPARA(sv)    (SvOK(sv) && ! SvCUR(sv))
+#define RsSIMPLE(sv)  (SvOK(sv) && (! SvPOK(sv) || SvCUR(sv)))
+#define RsPARA(sv)    (SvPOK(sv) && ! SvCUR(sv))

So it looks as though it has always called SvCUR on something that is
not necessarily a PV.  As of commit af7d13df559, it has also called
SvPVX on a potential non-PV.

Fixing this simply involves using SvPV instead of SvPVX.

I don’t know that t/io/open.t is the best place for the test, but all
the other ‘<...> line 42’ tests are there.
Make setdefout accept only NN

Just search through the source for GvIOp(PL_defoutgv) and you will see
that perl assumes that PL_defoutgv is never null.

I tried setting it to null from XS and got crashes, unsurprisingly.

The only CPAN user of PL_defoutgv sets it to STDOUT.
Get rid of ‘Not a format reference’

This commit:

commit 2dd78f96d61cc6382dc72214930c993567209597
Author: Jarkko Hietaniemi <jhi@iki.fi>
Date:   Sun Aug 6 01:33:55 2000 +0000

    Continue fixing the io warnings.  This also
    sort of fixes bug ID 20000802.003: the core dump
    is no more.  Whether the current behaviour is correct
    (giving a warning: "Not a format reference"), is another matter.

    p4raw-id: //depot/perl@6531

added a check to see whether the format GV’s name is null, and, if
so, it dies with ‘Not a format reference’.  Before that, that message
occurred only for lack of a GV.

The bug mentioned is now #3617, involving write(*STDOUT{IO}).  write
puts an implicit *{} around its argument.

*{$io} has historically been very buggy in its stringification, so
this patch seems to have been working around that bugginess, by fall-
ing back to the ‘Not a format reference’ error if the name couldn’t be
determined for ‘Undefined format "foo" called’.

*{$io} was fixed once and for all in 5.16.  It now stringifies as
*foopackage::__ANONIO__.

I don’t think producing a completetly different error based on the
name of the GV (whether it’s "foo" or "") is correct at all.  And the
patch that made it happen was just a fix for a crash that can’t hap-
pen any more.

So the only case that should produce ‘Not a format reference’ is that
in which there is no format GV (fgv).

I can prove that fgv is always set (see below), and has been at least
since 5.000, so that ‘Not a format reference’ actually could never
occur before 2dd78f96d61c.  (Actually, XS code could set PL_defoutgv
to null until the previous commit, but everything would start crashing
as a result, so it has never been done in practice.)

gv_efullname4 always returns a name, so checking SvPOK(tmpsv) is
redundant; checking whether the string buffer begins with a non-null
char is not even correct, as "\0foo" fails that test.

Proof that fgv is always set:

The current (prior to this commit) code in pp_enterwrite is like this:

    if (MAXARG == 0) {
	gv = PL_defoutgv;
	EXTEND(SP, 1);
    }
    else {
	gv = MUTABLE_GV(POPs);
	if (!gv)
	    gv = PL_defoutgv;
    }

If the stack value is null (which actually can’t happen), PL_defoutgv
is used.  PL_defoutgv can’t be null.

At this point, gv is set to something non-null.

    io = GvIO(gv);
    if (!io) {
	RETPUSHNO;
    }

Here we only set fgv to IoFMT_GV(io) if it is non-null.  Otherwise we
use gv, which we know is non-null.

    if (IoFMT_GV(io))
	fgv = IoFMT_GV(io);
    else
	fgv = gv;
Use the same top format error for ""

See also the previous commit.

2dd78f96 added the ‘Undefined top format called’ message for those
cases where a GV doesn’t have a name.  That was a bug that used to
happen with *{$io}, which can’t happen any more.

The code that 2dd78f96 added ended up changing a zero-length name to
be treated the same way as no name.  It also checked the length by
cheating and checking the first character instead.

Now that we have support for embedded nulls, that logic ends up wrong
for names like "\0foo".  And there is no need to treat "" differently
from "foo" anyway.

So this patch restores things the way they were before 2dd78f96.

It also improves the tests for ‘Undefined format’.

Writing tests for ‘Undefined top format’ was quite painful, as that
error seems to leave the internal state out of synch.  I suspect
PL_formtarget needs to be localised, or the error just needs to come
earlier in pp_leavewrite.  But I’ll save that for later, or for Dave
Mitchell. :-)
Make UNIVERSAL::can treats str and num the same way
util.c:report_wrongway_fh: Rmv redundant isGV check

Checking isGV_with_GP makes the isGV check redundant.  The only case
in which isGV could be true when isGV_with_GP is false could be a GV
playing PVBM, but those don’t exist any more.  When they did exist,
this check was probably wrong (and crashable).
util.c:report_wrongway_fh: Don’t create an SV

Now that sv_vcatpvfn supports HEKs directly, we don’t need to create a
temporary SV out of one.
util.c:report_evil_fh: Rmv redundant isGV check

Checking isGV_with_GP makes the isGV check redundant.  The only case
in which isGV could be true when isGV_with_GP is false could be a GV
playing PVBM, but those don’t exist any more.  When they did exist,
this check was probably wrong (and crashable).
util.c:report_wrongway_fh: Report name w/initial null

In the error message, we shouldn’t omit a handle whose name begins
with "\0", but, rather, a handle whose name has no length to it.
util.c:report_evil_fh: Rmv redundant SvPOK

newSVhek (used to create this SV) always returns an SvPOK scalar.
util.c:report_evil_fh: Report name w/initial null

In the error message, we shouldn’t omit a handle whose name begins
with "\0", but, rather, a handle whose name has no length to it.
Make open(... "<&", $fileno) respect magic

A magical variable is never SvPOK, but only SvPOKp.  The code for
checking whether a duplicatee is a numeric file descriptor was only
checking SvPOK.  So a regular variable containing a fileno-as-a-string
would work, such as the $a below, as would a stringified magical vari-
able ("$1"), but not $1 itself.

$ echo foo | perl -le '$a = "0"; open a, "<&", $a; warn <a>'
foo
$ echo foo | perl -le '"0" =~ /(.)/; open a, "<&", $1; warn <a>'
Can't use an undefined value as filehandle reference at -e line 1.
$ echo foo | perl -le '"0" =~ /(.)/; open a, "<&", "$1"; warn <a>'
foo

SvPOK variables are also SvPOKp, so checking only the latter suffices.
Make strict refs report $1 the same way as "$1"

A magical variable is never SvPOK, but only SvPOKp.  The code that
determined whether to put an ellipsis mark after a truncated symbol
name was only checking SvPOK, resulting in this discrepancy:

$ perl5.15.9 -e 'use strict; *{"a"x40}'
Can't use string ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"...) as a symbol ref while "strict refs" in use at -e line 1.
$ perl5.15.9 -e 'use strict; ("a"x40)=~/(.*)/; *{$1}'
Can't use string ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") as a symbol ref while "strict refs" in use at -e line 1.
$ perl5.15.9 -e 'use strict; ${"a"x40}'
Can't use string ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"...) as a SCALAR ref while "strict refs" in use at -e line 1.
$ perl5.15.9 -e 'use strict; ("a"x40)=~/(.*)/; ${$1}'
Can't use string ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") as a SCALAR ref while "strict refs" in use at -e line 1.

SvPOK variables are also SvPOKp, so checking just the latter suffices.
Make prototype call FETCH before checking CORE:: prefix

$ perl5.16.0 -e '"CORE::length" =~ /(.*)/; warn prototype $1;'
Warning: something's wrong at -e line 1.
$ perl5.16.0 -e 'warn prototype "CORE::length"'
_ at -e line 1.

Since sv_2cv calls get-magic, the easiest solution is to copy the
argument if it is magical.
Make warn handle magic vars (fixes [perl #97480])

pp_warn was checking flags before calling get-magic, resulting in sev-
eral bugs that I fixed all at once::
• warn now calls get-magic exactly once on its argument, when there
  is just one argument (it always worked correctly for multiple)
  [perl #97480].
• warn calls get-magic exactly once on $@ when falling back to it,
  instead of zero times.
• A tied variable returning an object that stringifies as an empty
  string is no longer ignored if the tied variable was not ROK
  before FETCH.
• A tied $@ containing a string, or $@ aliased to $1, is no
  longer ignored.
• A tied $@ that last returned a reference but will return a string on
  the next FETCH now gets "\t...caught" appended.
[perl #109542] Make num ops treat $1 as "$1"

Numeric ops were not taking magical variables into account.  So $1 (a
magical variable) would be treated differently from "$1" (a non-magi-
cal variable0.

In determining whether to use an integer operation, they would call
SvIV_please_nomg, and then check whether the sv was SvIOK as a result.

SvIV_please_nomg would call SvIV_nomg if the sv were SvPOK or SvNOK.

The problem here is that gmagical variables are never SvIOK, but
only SvIOKp.

In fact, the private flags are used differently for gmagical and non-
magical variables.  For non-gmagical variables, the private flag indi-
cates that there is a cached value.  If the public flag is not set,
then the cached value is imprecise.  For gmagical variables, imprecise
values are never cached; only the private flags are used, and they are
equivalent to the public flags on non-gmagical variables.

This commit changes SvIV_please_nomg to take gmagical variables
into account, using the newly-added sv_gmagical_2iv_please (see the
docs for it in the diff).  SvIV_please_nomg now returns true or
false, not void, since a subsequent SvIOK is not reliable.  So
‘SvIV_please_nomg(sv); if(SvIOK)’ becomes ‘if(SvIV_please_nomg(sv))’.
pp_negate: Don’t treat nummified str as num

I think it’s a bug that this prints 0:

$ ./perl -lIlib -MDevel::Peek -e '$x = "dogs"; 0+$x; Dump $x; print -$x'
SV = PVNV(0x802340) at 0x821b90
  REFCNT = 1
  FLAGS = (POK,pIOK,pNOK,pPOK)
  IV = 0
  NV = 0
  PV = 0x301620 "dogs"\0
  CUR = 4
  LEN = 16
0

This variable is a string, not a number.  The number 0 is just a
cached value.  It lacks the IOK flag precisely because the IV is not
representative of the actual value of the scalar.

This logic here is a little bit odd:

        if( !SvNIOK( sv ) && looks_like_number( sv ) ){
           SvIV_please( sv );
        }

	if ((flags & SVf_IOK) || ((flags & (SVp_IOK | SVp_NOK)) == SVp_IOK)) {

SvIV_please sets the flags on sv but then they are ignored when check-
ing for integrality.

To fix the bug mentioned above, I had to change this logic to use sv
directly, rather than the saved flags.

That meant that this bug was also fixed at the same time, since the
integer code is no longer bypassed when it is SvIV_please that sets
the integer flags:

$ ./perl -Ilib -le 'print -97656250000000000'
-97656250000000000
$ ./perl -Ilib -le 'print -"97656250000000000"'
-9.765625e+16
Fix perl #57706 for magical vars: -"-10"

Commit a5b92898 caused -"-10" to return 10, not "+10".  But it wasn’t
working for magical variables.

SvIV_please_nomg was fixed recently for magical variables, but not
SvIV_please, so change pp_negate to use that.

(Ironically, SvIV_please has never called magic, so the
SvIV_please_nomg variant never needed to exist.  So the two could
be merged.)
pp_negate and the Unicode Bug

$ ./perl -Ilib -Mutf8 -CO -le 'print -"3 apples"'
-3
$ ./perl -Ilib -Mutf8 -CO -le 'print -"3 μῆλα"'
-3 μῆλα

This has been this way since 5.10.1.  In 5.10.0, it was consistent:

$ perl5.10.0 -Mutf8 -CO -le 'print -"3 apples"'
-3
$ perl5.10.0 -Mutf8 -CO -le 'print -"3 μῆλα"'
-3

But the worst part is that we get a non-numeric warning now for a
string operation:

$ perl5.10.1 -Mutf8 -CO -lwe 'print -"3 μῆλα"'
Argument "\x{33}\x{20}..." isn't numeric in negation (-) at -e line 1.
-3 μῆλα

This goes back to commit a43d94f2c089, which by itself looks perfectly
correct (I won’t quote the diff here, as it is long; but it doesn’t
touch pp_negate):

commit a43d94f2c089c6f14197795daeebb7835550a747
Author: Nicholas Clark <nick@ccl4.org>
Date:   Mon Jan 7 18:24:39 2008 +0000

    Don't set the public IV or NV flags if the string converted from has
    trailing garbage. This behaviour is consistent with not setting the
    public IV or NV flags if the value is out of range for the type.

    p4raw-id: //depot/perl@32894

It seems that pp_negate was already buggy before that (or ‘validly’
assumed that numeric coercion would set public flags).  And it looks
as though commit 8eb28a70b2e is at fault here.

It changed this:

$ perl5.6.2 -Mutf8 -lwe 'print -"ð"'
-ð

to this:

$ perl5.8.1 -Mutf8 -lwe 'print -"ð"'
Argument "\x{f0}" isn't numeric in negation (-) at -e line 1.
0

to comply with what happens when the UTF8 flag is not set.  But it was
relying on bugs in sv_2iv, etc.

So, from 5.8.0 to 5.10.0 inclusive, unary negation prepends "-" if the
string begins with [A-Za-z], but from 5.10.1 onwards it behaves diffe-
rently depending on the internal UTF8 flag (even prepending "-" to
ASCII-only strings like "%apples" if the UTF8 flag is on).

This commit restores the 5.8.0-5.10.0 behaviour, which was at least
self-consistent.
pp_negate: Support magic big ints as strings

-$1 was treating $1 as a float even if the string consisted of an
integer, due to incorrect flag checks.  It was doing the same things
with tied variables returning str+int dualvars.

Simply checking whether the privates flags consist solely of SVp_IOK
(which works for tie variables returning pure integers--so I wasn’t
entirely wrong in adding that logic a few commits ago), isn’t suffi-
cient. For gmagical variables that have already had get-magic called
on them, the private flags are equivalent to public flags for other
variables.