← Index
NYTProf Performance Profile   « line view »
For split.pl
  Run on Thu Apr 20 02:05:47 2023
Reported on Thu Apr 20 18:31:09 2023

Filename/usr/lib/x86_64-linux-gnu/perl-base/File/Temp.pm
StatementsExecuted 21418771 statements in 68.1s
Subroutines
Calls P F Exclusive
Time
Inclusive
Time
Subroutine
133035118.89s28.9sFile::Temp::::_gettemp File::Temp::_gettemp
399105218.43s8.43sFile::Temp::::CORE:chmod File::Temp::CORE:chmod (opcode)
133035116.49s6.49sFile::Temp::::CORE:sysopen File::Temp::CORE:sysopen (opcode)
133035116.45s8.02sFile::Temp::::cmpstat File::Temp::cmpstat
133035115.37s7.84sFile::Temp::::_replace_XX File::Temp::_replace_XX
133035115.22s30.3sFile::Temp::::DESTROY File::Temp::DESTROY
133035114.62s4.62sFile::Temp::::CORE:unlink File::Temp::CORE:unlink (opcode)
133035114.54s38.6sFile::Temp::::tempfile File::Temp::tempfile
133035112.79s42.8sFile::Temp::::new File::Temp::new
133035112.18s20.3sFile::Temp::::unlink1 File::Temp::unlink1
266070211.33s8.72sFile::Temp::::_force_writable File::Temp::_force_writable
133035111.22s1.22sFile::Temp::::CORE:close File::Temp::CORE:close (opcode)
266070211.21s1.21sFile::Temp::::_parse_args File::Temp::_parse_args
1463385111.17s1.17sFile::Temp::::CORE:substcont File::Temp::CORE:substcont (opcode)
266070211.08s1.08sFile::Temp::::CORE:stat File::Temp::CORE:stat (opcode)
133035111.06s1.06sFile::Temp::::CORE:subst File::Temp::CORE:subst (opcode)
13303511958ms3.07sFile::Temp::::_wrap_file_spec_tmpdir File::Temp::_wrap_file_spec_tmpdir
13303511486ms486msFile::Temp::::CORE:ftfile File::Temp::CORE:ftfile (opcode)
13303511450ms450msFile::Temp::::CORE:ftis File::Temp::CORE:ftis (opcode)
13303511431ms431msFile::Temp::::CORE:ftdir File::Temp::CORE:ftdir (opcode)
13303511328ms328msFile::Temp::::unlink_on_destroy File::Temp::unlink_on_destroy
13303511298ms298msFile::Temp::::filename File::Temp::filename
26607011267ms267msFile::Temp::::safe_level File::Temp::safe_level
13303511243ms243msFile::Temp::::CORE:regcomp File::Temp::CORE:regcomp (opcode)
1112.17ms2.28msFile::Temp::::BEGIN@149 File::Temp::BEGIN@149
111795µs886µsFile::Temp::::BEGIN@168 File::Temp::BEGIN@168
111672µs926µsFile::Temp::::BEGIN@153 File::Temp::BEGIN@153
111511µs652µsFile::Temp::::BEGIN@152 File::Temp::BEGIN@152
111284µs707µsFile::Temp::::BEGIN@150 File::Temp::BEGIN@150
111238µs3.04msFile::Temp::::BEGIN@151 File::Temp::BEGIN@151
111180µs220µsFile::Temp::::BEGIN@167 File::Temp::BEGIN@167
11166µs67µsFile::Temp::::cleanup File::Temp::cleanup
11140µs107µsFile::Temp::::END File::Temp::END
11112µs12µsFile::Temp::::BEGIN@144 File::Temp::BEGIN@144
1119µs30µsFile::Temp::Dir::::BEGIN@2590File::Temp::Dir::BEGIN@2590
1119µs13µsFile::Temp::::BEGIN@147 File::Temp::BEGIN@147
1118µs19µsFile::Temp::::BEGIN@176 File::Temp::BEGIN@176
1114µs34µsFile::Temp::::BEGIN@216 File::Temp::BEGIN@216
1114µs8µsFile::Temp::::BEGIN@270 File::Temp::BEGIN@270
1114µs6µsFile::Temp::Dir::::BEGIN@2591File::Temp::Dir::BEGIN@2591
1114µs6µsFile::Temp::::BEGIN@145 File::Temp::BEGIN@145
1114µs9µsFile::Temp::::BEGIN@240 File::Temp::BEGIN@240
1114µs24µsFile::Temp::Dir::::BEGIN@2592File::Temp::Dir::BEGIN@2592
1113µs25µsFile::Temp::::BEGIN@146 File::Temp::BEGIN@146
1113µs19µsFile::Temp::::BEGIN@219 File::Temp::BEGIN@219
1113µs16µsFile::Temp::::BEGIN@229 File::Temp::BEGIN@229
1113µs17µsFile::Temp::::BEGIN@223 File::Temp::BEGIN@223
1112µs16µsFile::Temp::::BEGIN@227 File::Temp::BEGIN@227
1112µs15µsFile::Temp::::BEGIN@228 File::Temp::BEGIN@228
1112µs2µsFile::Temp::::BEGIN@148 File::Temp::BEGIN@148
1111µs1µsFile::Temp::::CORE:sort File::Temp::CORE:sort (opcode)
111700ns700nsFile::Temp::::__ANON__[:244] File::Temp::__ANON__[:244]
111500ns500nsFile::Temp::::__ANON__[:252] File::Temp::__ANON__[:252]
111400ns400nsFile::Temp::::__ANON__[:274] File::Temp::__ANON__[:274]
111200ns200nsFile::Temp::::__ANON__ File::Temp::__ANON__ (xsub)
0000s0sFile::Temp::Dir::::DESTROYFile::Temp::Dir::DESTROY
0000s0sFile::Temp::Dir::::STRINGIFYFile::Temp::Dir::STRINGIFY
0000s0sFile::Temp::Dir::::dirnameFile::Temp::Dir::dirname
0000s0sFile::Temp::Dir::::unlink_on_destroyFile::Temp::Dir::unlink_on_destroy
0000s0sFile::Temp::::NUMIFY File::Temp::NUMIFY
0000s0sFile::Temp::::STRINGIFY File::Temp::STRINGIFY
0000s0sFile::Temp::::__ANON__[:245] File::Temp::__ANON__[:245]
0000s0sFile::Temp::::__ANON__[:253] File::Temp::__ANON__[:253]
0000s0sFile::Temp::::__ANON__[:275] File::Temp::__ANON__[:275]
0000s0sFile::Temp::::_can_do_level File::Temp::_can_do_level
0000s0sFile::Temp::::_can_unlink_opened_file File::Temp::_can_unlink_opened_file
0000s0sFile::Temp::::_deferred_unlink File::Temp::_deferred_unlink
0000s0sFile::Temp::::_is_safe File::Temp::_is_safe
0000s0sFile::Temp::::_is_verysafe File::Temp::_is_verysafe
0000s0sFile::Temp::::mkdtemp File::Temp::mkdtemp
0000s0sFile::Temp::::mkstemp File::Temp::mkstemp
0000s0sFile::Temp::::mkstemps File::Temp::mkstemps
0000s0sFile::Temp::::mktemp File::Temp::mktemp
0000s0sFile::Temp::::newdir File::Temp::newdir
0000s0sFile::Temp::::tempdir File::Temp::tempdir
0000s0sFile::Temp::::tempnam File::Temp::tempnam
0000s0sFile::Temp::::tmpfile File::Temp::tmpfile
0000s0sFile::Temp::::tmpnam File::Temp::tmpnam
0000s0sFile::Temp::::top_system_uid File::Temp::top_system_uid
0000s0sFile::Temp::::unlink0 File::Temp::unlink0
Call graph for these subroutines as a Graphviz dot language file.
Line State
ments
Time
on line
Calls Time
in subs
Code
1package File::Temp; # git description: v0.2310-3-gc7148fe
2# ABSTRACT: return name and handle of a temporary file safely
3
41300nsour $VERSION = '0.2311';
5
6#pod =begin :__INTERNALS
7#pod
8#pod =head1 PORTABILITY
9#pod
10#pod This section is at the top in order to provide easier access to
11#pod porters. It is not expected to be rendered by a standard pod
12#pod formatting tool. Please skip straight to the SYNOPSIS section if you
13#pod are not trying to port this module to a new platform.
14#pod
15#pod This module is designed to be portable across operating systems and it
16#pod currently supports Unix, VMS, DOS, OS/2, Windows and Mac OS
17#pod (Classic). When porting to a new OS there are generally three main
18#pod issues that have to be solved:
19#pod
20#pod =over 4
21#pod
22#pod =item *
23#pod
24#pod Can the OS unlink an open file? If it can not then the
25#pod C<_can_unlink_opened_file> method should be modified.
26#pod
27#pod =item *
28#pod
29#pod Are the return values from C<stat> reliable? By default all the
30#pod return values from C<stat> are compared when unlinking a temporary
31#pod file using the filename and the handle. Operating systems other than
32#pod unix do not always have valid entries in all fields. If utility function
33#pod C<File::Temp::unlink0> fails then the C<stat> comparison should be
34#pod modified accordingly.
35#pod
36#pod =item *
37#pod
38#pod Security. Systems that can not support a test for the sticky bit
39#pod on a directory can not use the MEDIUM and HIGH security tests.
40#pod The C<_can_do_level> method should be modified accordingly.
41#pod
42#pod =back
43#pod
44#pod =end :__INTERNALS
45#pod
46#pod =head1 SYNOPSIS
47#pod
48#pod use File::Temp qw/ tempfile tempdir /;
49#pod
50#pod $fh = tempfile();
51#pod ($fh, $filename) = tempfile();
52#pod
53#pod ($fh, $filename) = tempfile( $template, DIR => $dir);
54#pod ($fh, $filename) = tempfile( $template, SUFFIX => '.dat');
55#pod ($fh, $filename) = tempfile( $template, TMPDIR => 1 );
56#pod
57#pod binmode( $fh, ":utf8" );
58#pod
59#pod $dir = tempdir( CLEANUP => 1 );
60#pod ($fh, $filename) = tempfile( DIR => $dir );
61#pod
62#pod Object interface:
63#pod
64#pod require File::Temp;
65#pod use File::Temp ();
66#pod use File::Temp qw/ :seekable /;
67#pod
68#pod $fh = File::Temp->new();
69#pod $fname = $fh->filename;
70#pod
71#pod $fh = File::Temp->new(TEMPLATE => $template);
72#pod $fname = $fh->filename;
73#pod
74#pod $tmp = File::Temp->new( UNLINK => 0, SUFFIX => '.dat' );
75#pod print $tmp "Some data\n";
76#pod print "Filename is $tmp\n";
77#pod $tmp->seek( 0, SEEK_END );
78#pod
79#pod $dir = File::Temp->newdir(); # CLEANUP => 1 by default
80#pod
81#pod The following interfaces are provided for compatibility with
82#pod existing APIs. They should not be used in new code.
83#pod
84#pod MkTemp family:
85#pod
86#pod use File::Temp qw/ :mktemp /;
87#pod
88#pod ($fh, $file) = mkstemp( "tmpfileXXXXX" );
89#pod ($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix);
90#pod
91#pod $tmpdir = mkdtemp( $template );
92#pod
93#pod $unopened_file = mktemp( $template );
94#pod
95#pod POSIX functions:
96#pod
97#pod use File::Temp qw/ :POSIX /;
98#pod
99#pod $file = tmpnam();
100#pod $fh = tmpfile();
101#pod
102#pod ($fh, $file) = tmpnam();
103#pod
104#pod Compatibility functions:
105#pod
106#pod $unopened_file = File::Temp::tempnam( $dir, $pfx );
107#pod
108#pod =head1 DESCRIPTION
109#pod
110#pod C<File::Temp> can be used to create and open temporary files in a safe
111#pod way. There is both a function interface and an object-oriented
112#pod interface. The File::Temp constructor or the tempfile() function can
113#pod be used to return the name and the open filehandle of a temporary
114#pod file. The tempdir() function can be used to create a temporary
115#pod directory.
116#pod
117#pod The security aspect of temporary file creation is emphasized such that
118#pod a filehandle and filename are returned together. This helps guarantee
119#pod that a race condition can not occur where the temporary file is
120#pod created by another process between checking for the existence of the
121#pod file and its opening. Additional security levels are provided to
122#pod check, for example, that the sticky bit is set on world writable
123#pod directories. See L<"safe_level"> for more information.
124#pod
125#pod For compatibility with popular C library functions, Perl implementations of
126#pod the mkstemp() family of functions are provided. These are, mkstemp(),
127#pod mkstemps(), mkdtemp() and mktemp().
128#pod
129#pod Additionally, implementations of the standard L<POSIX|POSIX>
130#pod tmpnam() and tmpfile() functions are provided if required.
131#pod
132#pod Implementations of mktemp(), tmpnam(), and tempnam() are provided,
133#pod but should be used with caution since they return only a filename
134#pod that was valid when function was called, so cannot guarantee
135#pod that the file will not exist by the time the caller opens the filename.
136#pod
137#pod Filehandles returned by these functions support the seekable methods.
138#pod
139#pod =cut
140
141# Toolchain targets v5.8.1, but we'll try to support back to v5.6 anyway.
142# It might be possible to make this v5.5, but many v5.6isms are creeping
143# into the code and tests.
144229µs112µs
# spent 12µs within File::Temp::BEGIN@144 which was called: # once (12µs+0s) by main::BEGIN@18 at line 144
use 5.006;
# spent 12µs making 1 call to File::Temp::BEGIN@144
145215µs28µs
# spent 6µs (4+2) within File::Temp::BEGIN@145 which was called: # once (4µs+2µs) by main::BEGIN@18 at line 145
use strict;
# spent 6µs making 1 call to File::Temp::BEGIN@145 # spent 2µs making 1 call to strict::import
146218µs247µs
# spent 25µs (3+22) within File::Temp::BEGIN@146 which was called: # once (3µs+22µs) by main::BEGIN@18 at line 146
use Carp;
# spent 25µs making 1 call to File::Temp::BEGIN@146 # spent 22µs making 1 call to Exporter::import
147323µs318µs
# spent 13µs (9+4) within File::Temp::BEGIN@147 which was called: # once (9µs+4µs) by main::BEGIN@18 at line 147
use File::Spec 0.8;
# spent 13µs making 1 call to File::Temp::BEGIN@147 # spent 4µs making 1 call to UNIVERSAL::VERSION # spent 200ns making 1 call to File::Temp::__ANON__
148215µs12µs
# spent 2µs within File::Temp::BEGIN@148 which was called: # once (2µs+0s) by main::BEGIN@18 at line 148
use Cwd ();
# spent 2µs making 1 call to File::Temp::BEGIN@148
1493112µs32.31ms
# spent 2.28ms (2.17+116µs) within File::Temp::BEGIN@149 which was called: # once (2.17ms+116µs) by main::BEGIN@18 at line 149
use File::Path 2.06 qw/ rmtree /;
# spent 2.28ms making 1 call to File::Temp::BEGIN@149 # spent 23µs making 1 call to Exporter::import # spent 8µs making 1 call to UNIVERSAL::VERSION
1503109µs3827µs
# spent 707µs (284+423) within File::Temp::BEGIN@150 which was called: # once (284µs+423µs) by main::BEGIN@18 at line 150
use Fcntl 1.03;
# spent 707µs making 1 call to File::Temp::BEGIN@150 # spent 115µs making 1 call to Exporter::import # spent 5µs making 1 call to UNIVERSAL::VERSION
151293µs23.06ms
# spent 3.04ms (238µs+2.81) within File::Temp::BEGIN@151 which was called: # once (238µs+2.81ms) by main::BEGIN@18 at line 151
use IO::Seekable; # For SEEK_*
# spent 3.04ms making 1 call to File::Temp::BEGIN@151 # spent 14µs making 1 call to Exporter::import
1522108µs2663µs
# spent 652µs (511+141) within File::Temp::BEGIN@152 which was called: # once (511µs+141µs) by main::BEGIN@18 at line 152
use Errno;
# spent 652µs making 1 call to File::Temp::BEGIN@152 # spent 11µs making 1 call to Exporter::import
153295µs2956µs
# spent 926µs (672+254) within File::Temp::BEGIN@153 which was called: # once (672µs+254µs) by main::BEGIN@18 at line 153
use Scalar::Util 'refaddr';
# spent 926µs making 1 call to File::Temp::BEGIN@153 # spent 29µs making 1 call to Exporter::import
15411µsrequire VMS::Stdio if $^O eq 'VMS';
155
156# pre-emptively load Carp::Heavy. If we don't when we run out of file
157# handles and attempt to call croak() we get an error message telling
158# us that Carp::Heavy won't load rather than an error telling us we
159# have run out of file handles. We either preload croak() or we
160# switch the calls to croak from _gettemp() to use die.
161281µseval { require Carp::Heavy; };
162
163# Need the Symbol package if we are running older perl
1641300nsrequire Symbol if $] < 5.006;
165
166### For the OO interface
167397µs3243µs
# spent 220µs (180+40) within File::Temp::BEGIN@167 which was called: # once (180µs+40µs) by main::BEGIN@18 at line 167
use parent 0.221 qw/ IO::Handle IO::Seekable /;
# spent 220µs making 1 call to File::Temp::BEGIN@167 # spent 17µs making 1 call to parent::import # spent 5µs making 1 call to UNIVERSAL::VERSION
16813µs119µs
# spent 886µs (795+91) within File::Temp::BEGIN@168 which was called: # once (795µs+91µs) by main::BEGIN@18 at line 169
use overload '""' => "STRINGIFY", '0+' => "NUMIFY",
# spent 19µs making 1 call to overload::import
169193µs1886µs fallback => 1;
# spent 886µs making 1 call to File::Temp::BEGIN@168
170
1711200nsour $DEBUG = 0;
1721100nsour $KEEP_ALL = 0;
173
174# We are exporting functions
175
176378µs330µs
# spent 19µs (8+11) within File::Temp::BEGIN@176 which was called: # once (8µs+11µs) by main::BEGIN@18 at line 176
use Exporter 5.57 'import'; # 5.57 lets us import 'import'
# spent 19µs making 1 call to File::Temp::BEGIN@176 # spent 6µs making 1 call to UNIVERSAL::VERSION # spent 5µs making 1 call to Exporter::import
177
178# Export list - to allow fine tuning of export table
179
18012µsour @EXPORT_OK = qw{
181 tempfile
182 tempdir
183 tmpnam
184 tmpfile
185 mktemp
186 mkstemp
187 mkstemps
188 mkdtemp
189 unlink0
190 cleanup
191 SEEK_SET
192 SEEK_CUR
193 SEEK_END
194 };
195
196# Groups of functions for export
197
19812µsour %EXPORT_TAGS = (
199 'POSIX' => [qw/ tmpnam tmpfile /],
200 'mktemp' => [qw/ mktemp mkstemp mkstemps mkdtemp/],
201 'seekable' => [qw/ SEEK_SET SEEK_CUR SEEK_END /],
202 );
203
204# add contents of these tags to @EXPORT
20512µs115µsExporter::export_tags('POSIX','mktemp','seekable');
# spent 15µs making 1 call to Exporter::export_tags
206
207# This is a list of characters that can be used in random filenames
208
20916µsmy @CHARS = (qw/ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
210 a b c d e f g h i j k l m n o p q r s t u v w x y z
211 0 1 2 3 4 5 6 7 8 9 _
212 /);
213
214# Maximum number of tries to make a temp file before failing
215
216217µs264µs
# spent 34µs (4+30) within File::Temp::BEGIN@216 which was called: # once (4µs+30µs) by main::BEGIN@18 at line 216
use constant MAX_TRIES => 1000;
# spent 34µs making 1 call to File::Temp::BEGIN@216 # spent 30µs making 1 call to constant::import
217
218# Minimum number of X characters that should be in a template
219218µs234µs
# spent 19µs (3+16) within File::Temp::BEGIN@219 which was called: # once (3µs+16µs) by main::BEGIN@18 at line 219
use constant MINX => 4;
# spent 19µs making 1 call to File::Temp::BEGIN@219 # spent 16µs making 1 call to constant::import
220
221# Default template when no template supplied
222
223214µs230µs
# spent 17µs (3+14) within File::Temp::BEGIN@223 which was called: # once (3µs+14µs) by main::BEGIN@18 at line 223
use constant TEMPXXX => 'X' x 10;
# spent 17µs making 1 call to File::Temp::BEGIN@223 # spent 14µs making 1 call to constant::import
224
225# Constants for the security level
226
227212µs229µs
# spent 16µs (2+13) within File::Temp::BEGIN@227 which was called: # once (2µs+13µs) by main::BEGIN@18 at line 227
use constant STANDARD => 0;
# spent 16µs making 1 call to File::Temp::BEGIN@227 # spent 13µs making 1 call to constant::import
228212µs227µs
# spent 15µs (2+12) within File::Temp::BEGIN@228 which was called: # once (2µs+12µs) by main::BEGIN@18 at line 228
use constant MEDIUM => 1;
# spent 15µs making 1 call to File::Temp::BEGIN@228 # spent 12µs making 1 call to constant::import
229238µs229µs
# spent 16µs (3+13) within File::Temp::BEGIN@229 which was called: # once (3µs+13µs) by main::BEGIN@18 at line 229
use constant HIGH => 2;
# spent 16µs making 1 call to File::Temp::BEGIN@229 # spent 13µs making 1 call to constant::import
230
231# OPENFLAGS. If we defined the flag to use with Sysopen here this gives
232# us an optimisation when many temporary files are requested
233
2341100nsmy $OPENFLAGS = O_CREAT | O_EXCL | O_RDWR;
2351200nsmy $LOCKFLAG;
236
2371900nsunless ($^O eq 'MacOS') {
2381400ns for my $oflag (qw/ NOFOLLOW BINARY LARGEFILE NOINHERIT /) {
23942µs my ($bit, $func) = (0, "Fcntl::O_" . $oflag);
2402124µs214µs
# spent 9µs (4+5) within File::Temp::BEGIN@240 which was called: # once (4µs+5µs) by main::BEGIN@18 at line 240
no strict 'refs';
# spent 9µs making 1 call to File::Temp::BEGIN@240 # spent 5µs making 1 call to strict::unimport
24142µs $OPENFLAGS |= $bit if eval {
242 # Make sure that redefined die handlers do not cause problems
243 # e.g. CGI::Carp
24457µs
# spent 700ns within File::Temp::__ANON__[/usr/lib/x86_64-linux-gnu/perl-base/File/Temp.pm:244] which was called: # once (700ns+0s) by Fcntl::O_NOINHERIT at line 246
local $SIG{__DIE__} = sub {};
24543µs local $SIG{__WARN__} = sub {};
246438µs530µs $bit = &$func();
# spent 18µs making 1 call to Fcntl::O_NOINHERIT # spent 6µs making 1 call to Fcntl::O_NOFOLLOW # spent 3µs making 1 call to Fcntl::O_BINARY # spent 2µs making 1 call to Fcntl::O_LARGEFILE # spent 700ns making 1 call to File::Temp::__ANON__[File/Temp.pm:244]
24734µs 1;
248 };
249 }
250 # Special case O_EXLOCK
25110s $LOCKFLAG = eval {
25222µs
# spent 500ns within File::Temp::__ANON__[/usr/lib/x86_64-linux-gnu/perl-base/File/Temp.pm:252] which was called: # once (500ns+0s) by Fcntl::O_EXLOCK at line 254
local $SIG{__DIE__} = sub {};
2531700ns local $SIG{__WARN__} = sub {};
25418µs28µs &Fcntl::O_EXLOCK();
# spent 7µs making 1 call to Fcntl::O_EXLOCK # spent 500ns making 1 call to File::Temp::__ANON__[File/Temp.pm:252]
255 };
256}
257
258# On some systems the O_TEMPORARY flag can be used to tell the OS
259# to automatically remove the file when it is closed. This is fine
260# in most cases but not if tempfile is called with UNLINK=>0 and
261# the filename is requested -- in the case where the filename is to
262# be passed to another routine. This happens on windows. We overcome
263# this by using a second open flags variable
264
2651200nsmy $OPENTEMPFLAGS = $OPENFLAGS;
2661600nsunless ($^O eq 'MacOS') {
2671300ns for my $oflag (qw/ TEMPORARY /) {
2681400ns my ($bit, $func) = (0, "Fcntl::O_" . $oflag);
2691100ns local($@);
2702435µs211µs
# spent 8µs (4+3) within File::Temp::BEGIN@270 which was called: # once (4µs+3µs) by main::BEGIN@18 at line 270
no strict 'refs';
# spent 8µs making 1 call to File::Temp::BEGIN@270 # spent 3µs making 1 call to strict::unimport
2711200ns $OPENTEMPFLAGS |= $bit if eval {
272 # Make sure that redefined die handlers do not cause problems
273 # e.g. CGI::Carp
27422µs
# spent 400ns within File::Temp::__ANON__[/usr/lib/x86_64-linux-gnu/perl-base/File/Temp.pm:274] which was called: # once (400ns+0s) by Fcntl::O_TEMPORARY at line 276
local $SIG{__DIE__} = sub {};
27511µs local $SIG{__WARN__} = sub {};
27618µs27µs $bit = &$func();
# spent 6µs making 1 call to Fcntl::O_TEMPORARY # spent 400ns making 1 call to File::Temp::__ANON__[File/Temp.pm:274]
277 1;
278 };
279 }
280}
281
282# Private hash tracking which files have been created by each process id via the OO interface
2831100nsmy %FILES_CREATED_BY_OBJECT;
284
285# INTERNAL ROUTINES - not to be used outside of package
286
287# Generic routine for getting a temporary filename
288# modelled on OpenBSD _gettemp() in mktemp.c
289
290# The template must contain X's that are to be replaced
291# with the random values
292
293# Arguments:
294
295# TEMPLATE - string containing the XXXXX's that is converted
296# to a random filename and opened if required
297
298# Optionally, a hash can also be supplied containing specific options
299# "open" => if true open the temp file, else just return the name
300# default is 0
301# "mkdir"=> if true, we are creating a temp directory rather than tempfile
302# default is 0
303# "suffixlen" => number of characters at end of PATH to be ignored.
304# default is 0.
305# "unlink_on_close" => indicates that, if possible, the OS should remove
306# the file as soon as it is closed. Usually indicates
307# use of the O_TEMPORARY flag to sysopen.
308# Usually irrelevant on unix
309# "use_exlock" => Indicates that O_EXLOCK should be used. Default is false.
310# "file_permissions" => file permissions for sysopen(). Default is 0600.
311
312# Optionally a reference to a scalar can be passed into the function
313# On error this will be used to store the reason for the error
314# "ErrStr" => \$errstr
315
316# "open" and "mkdir" can not both be true
317# "unlink_on_close" is not used when "mkdir" is true.
318
319# The default options are equivalent to mktemp().
320
321# Returns:
322# filehandle - open file handle (if called with doopen=1, else undef)
323# temp name - name of the temp file or directory
324
325# For example:
326# ($fh, $name) = _gettemp($template, "open" => 1);
327
328# for the current version, failures are associated with
329# stored in an error string and returned to give the reason whilst debugging
330# This routine is not called by any external function
331
# spent 28.9s (8.89+20.0) within File::Temp::_gettemp which was called 133035 times, avg 217µs/call: # 133035 times (8.89s+20.0s) by File::Temp::tempfile at line 1482, avg 217µs/call
sub _gettemp {
332
33313303556.2ms croak 'Usage: ($fh, $name) = _gettemp($template, OPTIONS);'
334 unless scalar(@_) >= 1;
335
336 # the internal error string - expect it to be overridden
337 # Need this in case the caller decides not to supply us a value
338 # need an anonymous scalar
33913303535.4ms my $tempErrStr;
340
341 # Default options
3421330351.67s my %options = (
343 "open" => 0,
344 "mkdir" => 0,
345 "suffixlen" => 0,
346 "unlink_on_close" => 0,
347 "use_exlock" => 0,
348 "ErrStr" => \$tempErrStr,
349 "file_permissions" => undef,
350 );
351
352 # Read the template
35313303543.2ms my $template = shift;
35413303528.1ms if (ref($template)) {
355 # Use a warning here since we have not yet merged ErrStr
356 carp "File::Temp::_gettemp: template must not be a reference";
357 return ();
358 }
359
360 # Check that the number of entries on stack are even
36113303569.3ms if (scalar(@_) % 2 != 0) {
362 # Use a warning here since we have not yet merged ErrStr
363 carp "File::Temp::_gettemp: Must have even number of options";
364 return ();
365 }
366
367 # Read the options and merge with defaults
368133035542ms %options = (%options, @_) if @_;
369
370 # Make sure the error string is set to undef
37113303568.4ms ${$options{ErrStr}} = undef;
372
373 # Can not open the file and make a directory in a single call
374133035104ms if ($options{"open"} && $options{"mkdir"}) {
375 ${$options{ErrStr}} = "doopen and domkdir can not both be true\n";
376 return ();
377 }
378
379 # Find the start of the end of the Xs (position of last X)
380 # Substr starts from 0
38113303589.8ms my $start = length($template) - 1 - $options{"suffixlen"};
382
383 # Check that we have at least MINX x X (e.g. 'XXXX") at the end of the string
384 # (taking suffixlen into account). Any fewer is insecure.
385
386 # Do it using substr - no reason to use a pattern match since
387 # we know where we are looking and what we are looking for
388
389133035175ms if (substr($template, $start - MINX + 1, MINX) ne 'X' x MINX) {
390 ${$options{ErrStr}} = "The template must end with at least ".
391 MINX . " 'X' characters\n";
392 return ();
393 }
394
395 # Replace all the X at the end of the substring with a
396 # random character or just all the XX at the end of a full string.
397 # Do it as an if, since the suffix adjusts which section to replace
398 # and suffixlen=0 returns nothing if used in the substr directly
399 # and generate a full path from the template
400
401133035226ms1330357.84s my $path = _replace_XX($template, $options{"suffixlen"});
# spent 7.84s making 133035 calls to File::Temp::_replace_XX, avg 59µs/call
402
403 # Split the path into constituent parts - eventually we need to check
404 # whether the directory exists
405 # We need to know whether we are making a temp directory
406 # or a tempfile
407
40813303532.0ms my ($volume, $directories, $file);
409 my $parent; # parent directory
41013303569.9ms if ($options{"mkdir"}) {
411 # There is no filename at the end
412 ($volume, $directories, $file) = File::Spec->splitpath( $path, 1);
413
414 # The parent is then $directories without the last directory
415 # Split the directory and put it back together again
416 my @dirs = File::Spec->splitdir($directories);
417
418 # If @dirs only has one entry (i.e. the directory template) that means
419 # we are in the current directory
420 if ($#dirs == 0) {
421 $parent = File::Spec->curdir;
422 } else {
423
424 if ($^O eq 'VMS') { # need volume to avoid relative dir spec
425 $parent = File::Spec->catdir($volume, @dirs[0..$#dirs-1]);
426 $parent = 'sys$disk:[]' if $parent eq '';
427 } else {
428
429 # Put it back together without the last one
430 $parent = File::Spec->catdir(@dirs[0..$#dirs-1]);
431
432 # ...and attach the volume (no filename)
433 $parent = File::Spec->catpath($volume, $parent, '');
434 }
435
436 }
437
438 } else {
439
440 # Get rid of the last filename (use File::Basename for this?)
441133035550ms1330352.73s ($volume, $directories, $file) = File::Spec->splitpath( $path );
# spent 2.73s making 133035 calls to File::Spec::Unix::splitpath, avg 21µs/call
442
443 # Join up without the file part
444133035484ms133035777ms $parent = File::Spec->catpath($volume,$directories,'');
# spent 777ms making 133035 calls to File::Spec::Unix::catpath, avg 6µs/call
445
446 # If $parent is empty replace with curdir
44713303547.1ms $parent = File::Spec->curdir
448 unless $directories ne '';
449
450 }
451
452 # Check that the parent directories exist
453 # Do this even for the case where we are simply returning a name
454 # not a file -- no point returning a name that includes a directory
455 # that does not exist or is not writable
456
457133035866ms133035450ms unless (-e $parent) {
# spent 450ms making 133035 calls to File::Temp::CORE:ftis, avg 3µs/call
458 ${$options{ErrStr}} = "Parent directory ($parent) does not exist";
459 return ();
460 }
461133035774ms133035431ms unless (-d $parent) {
# spent 431ms making 133035 calls to File::Temp::CORE:ftdir, avg 3µs/call
462 ${$options{ErrStr}} = "Parent directory ($parent) is not a directory";
463 return ();
464 }
465
466 # Check the stickiness of the directory and chown giveaway if required
467 # If the directory is world writable the sticky bit
468 # must be set
469
470133035360ms266070267ms if (File::Temp->safe_level == MEDIUM) {
# spent 267ms making 266070 calls to File::Temp::safe_level, avg 1µs/call
471 my $safeerr;
472 unless (_is_safe($parent,\$safeerr)) {
473 ${$options{ErrStr}} = "Parent directory ($parent) is not safe ($safeerr)";
474 return ();
475 }
476 } elsif (File::Temp->safe_level == HIGH) {
477 my $safeerr;
478 unless (_is_verysafe($parent, \$safeerr)) {
479 ${$options{ErrStr}} = "Parent directory ($parent) is not safe ($safeerr)";
480 return ();
481 }
482 }
483
48413303577.4ms my $perms = $options{file_permissions};
48513303545.2ms my $has_perms = defined $perms;
48613303545.6ms $perms = 0600 unless $has_perms;
487
488 # Now try MAX_TRIES time to open the file
489133035110ms for (my $i = 0; $i < MAX_TRIES; $i++) {
490
491 # Try to open the file if requested
49213303549.7ms if ($options{"open"}) {
49313303519.9ms my $fh;
494
495 # If we are running before perl5.6.0 we can not auto-vivify
49613303546.6ms if ($] < 5.006) {
497 $fh = &Symbol::gensym;
498 }
499
500 # Try to make sure this will be marked close-on-exec
501 # XXX: Win32 doesn't respect this, nor the proper fcntl,
502 # but may have O_NOINHERIT. This may or may not be in Fcntl.
503133035358ms local $^F = 2;
504
505 # Attempt to open the file
50613303529.2ms my $open_success = undef;
507133035140ms if ( $^O eq 'VMS' and $options{"unlink_on_close"} && !$KEEP_ALL) {
508 # make it auto delete on close by setting FAB$V_DLT bit
509 $fh = VMS::Stdio::vmssysopen($path, $OPENFLAGS, $perms, 'fop=dlt');
510 $open_success = $fh;
511 } else {
51213303584.9ms my $flags = ( ($options{"unlink_on_close"} && !$KEEP_ALL) ?
513 $OPENTEMPFLAGS :
514 $OPENFLAGS );
51513303534.3ms $flags |= $LOCKFLAG if (defined $LOCKFLAG && $options{use_exlock});
5161330357.26s1330356.49s $open_success = sysopen($fh, $path, $flags, $perms);
# spent 6.49s making 133035 calls to File::Temp::CORE:sysopen, avg 49µs/call
517 }
51813303534.5ms if ( $open_success ) {
519
520 # in case of odd umask force rw
5211330351.47s1330351.04s chmod($perms, $path) unless $has_perms;
# spent 1.04s making 133035 calls to File::Temp::CORE:chmod, avg 8µs/call
522
523 # Opened successfully - return file handle and name
524133035772ms return ($fh, $path);
525
526 } else {
527
528 # Error opening file - abort with error
529 # if the reason was anything but EEXIST
53013.15ms18µs unless ($!{EEXIST}) {
# spent 8µs making 1 call to Errno::_tie_it
531 ${$options{ErrStr}} = "Could not create temp file $path: $!";
532 return ();
533 }
534
535 # Loop round for another try
536
537 }
538 } elsif ($options{"mkdir"}) {
539
540 # Open the temp directory
541 if (mkdir( $path, 0700)) {
542 # in case of odd umask
543 chmod(0700, $path);
544
545 return undef, $path;
546 } else {
547
548 # Abort with error if the reason for failure was anything
549 # except EEXIST
550 unless ($!{EEXIST}) {
551 ${$options{ErrStr}} = "Could not create directory $path: $!";
552 return ();
553 }
554
555 # Loop round for another try
556
557 }
558
559 } else {
560
561 # Return true if the file can not be found
562 # Directory has been checked previously
563
564 return (undef, $path) unless -e $path;
565
566 # Try again until MAX_TRIES
567
568 }
569
570 # Did not successfully open the tempfile/dir
571 # so try again with a different set of random letters
572 # No point in trying to increment unless we have only
573 # 1 X say and the randomness could come up with the same
574 # file MAX_TRIES in a row.
575
576 # Store current attempt - in principle this implies that the
577 # 3rd time around the open attempt that the first temp file
578 # name could be generated again. Probably should store each
579 # attempt and make sure that none are repeated
580
581 my $original = $path;
582 my $counter = 0; # Stop infinite loop
583 my $MAX_GUESS = 50;
584
585 do {
586
587 # Generate new name from original template
588 $path = _replace_XX($template, $options{"suffixlen"});
589
590 $counter++;
591
592 } until ($path ne $original || $counter > $MAX_GUESS);
593
594 # Check for out of control looping
595 if ($counter > $MAX_GUESS) {
596 ${$options{ErrStr}} = "Tried to get a new temp name different to the previous value $MAX_GUESS times.\nSomething wrong with template?? ($template)";
597 return ();
598 }
599
600 }
601
602 # If we get here, we have run out of tries
603 ${ $options{ErrStr} } = "Have exceeded the maximum number of attempts ("
604 . MAX_TRIES . ") to open temp file/dir";
605
606 return ();
607
608}
609
610# Internal routine to replace the XXXX... with random characters
611# This has to be done by _gettemp() every time it fails to
612# open a temp file/dir
613
614# Arguments: $template (the template with XXX),
615# $ignore (number of characters at end to ignore)
616
617# Returns: modified template
618
619
# spent 7.84s (5.37+2.47) within File::Temp::_replace_XX which was called 133035 times, avg 59µs/call: # 133035 times (5.37s+2.47s) by File::Temp::_gettemp at line 401, avg 59µs/call
sub _replace_XX {
620
62113303553.0ms croak 'Usage: _replace_XX($template, $ignore)'
622 unless scalar(@_) == 2;
623
62413303564.4ms my ($path, $ignore) = @_;
625
626 # Do it as an if, since the suffix adjusts which section to replace
627 # and suffixlen=0 returns nothing if used in the substr directly
628 # Alternatively, could simply set $ignore to length($path)-1
629 # Don't want to always use substr when not required though.
630133035275ms my $end = ( $] >= 5.006 ? "\\z" : "\\Z" );
631
63213303576.2ms if ($ignore) {
633 substr($path, 0, - $ignore) =~ s/X(?=X*$end)/$CHARS[ int( rand( @CHARS ) ) ]/ge;
634 } else {
6351330357.14s17294552.47s $path =~ s/X(?=X*$end)/$CHARS[ int( rand( @CHARS ) ) ]/ge;
# spent 1.17s making 1463385 calls to File::Temp::CORE:substcont, avg 797ns/call # spent 1.06s making 133035 calls to File::Temp::CORE:subst, avg 8µs/call # spent 243ms making 133035 calls to File::Temp::CORE:regcomp, avg 2µs/call
636 }
637133035395ms return $path;
638}
639
640# Internal routine to force a temp file to be writable after
641# it is created so that we can unlink it. Windows seems to occasionally
642# force a file to be readonly when written to certain temp locations
643
# spent 8.72s (1.33+7.39) within File::Temp::_force_writable which was called 266070 times, avg 33µs/call: # 133035 times (777ms+3.67s) by File::Temp::DESTROY at line 1261, avg 33µs/call # 133035 times (551ms+3.72s) by File::Temp::unlink1 at line 2291, avg 32µs/call
sub _force_writable {
64426607083.2ms my $file = shift;
6452660709.08s2660707.39s chmod 0600, $file;
# spent 7.39s making 266070 calls to File::Temp::CORE:chmod, avg 28µs/call
646}
647
648# internal routine to check to see if the directory is safe
649# First checks to see if the directory is not owned by the
650# current user or root. Then checks to see if anyone else
651# can write to the directory and if so, checks to see if
652# it has the sticky bit set
653
654# Will not work on systems that do not support sticky bit
655
656#Args: directory path to check
657# Optionally: reference to scalar to contain error message
658# Returns true if the path is safe and false otherwise.
659# Returns undef if can not even run stat() on the path
660
661# This routine based on version written by Tom Christiansen
662
663# Presumably, by the time we actually attempt to create the
664# file or directory in this directory, it may not be safe
665# anymore... Have to run _is_safe directly after the open.
666
667sub _is_safe {
668
669 my $path = shift;
670 my $err_ref = shift;
671
672 # Stat path
673 my @info = stat($path);
674 unless (scalar(@info)) {
675 $$err_ref = "stat(path) returned no values";
676 return 0;
677 }
678 ;
679 return 1 if $^O eq 'VMS'; # owner delete control at file level
680
681 # Check to see whether owner is neither superuser (or a system uid) nor me
682 # Use the effective uid from the $> variable
683 # UID is in [4]
684 if ($info[4] > File::Temp->top_system_uid() && $info[4] != $>) {
685
686 Carp::cluck(sprintf "uid=$info[4] topuid=%s euid=$> path='$path'",
687 File::Temp->top_system_uid());
688
689 $$err_ref = "Directory owned neither by root nor the current user"
690 if ref($err_ref);
691 return 0;
692 }
693
694 # check whether group or other can write file
695 # use 066 to detect either reading or writing
696 # use 022 to check writability
697 # Do it with S_IWOTH and S_IWGRP for portability (maybe)
698 # mode is in info[2]
699 if (($info[2] & &Fcntl::S_IWGRP) || # Is group writable?
700 ($info[2] & &Fcntl::S_IWOTH) ) { # Is world writable?
701 # Must be a directory
702 unless (-d $path) {
703 $$err_ref = "Path ($path) is not a directory"
704 if ref($err_ref);
705 return 0;
706 }
707 # Must have sticky bit set
708 unless (-k $path) {
709 $$err_ref = "Sticky bit not set on $path when dir is group|world writable"
710 if ref($err_ref);
711 return 0;
712 }
713 }
714
715 return 1;
716}
717
718# Internal routine to check whether a directory is safe
719# for temp files. Safer than _is_safe since it checks for
720# the possibility of chown giveaway and if that is a possibility
721# checks each directory in the path to see if it is safe (with _is_safe)
722
723# If _PC_CHOWN_RESTRICTED is not set, does the full test of each
724# directory anyway.
725
726# Takes optional second arg as scalar ref to error reason
727
728sub _is_verysafe {
729
730 # Need POSIX - but only want to bother if really necessary due to overhead
731 require POSIX;
732
733 my $path = shift;
734 print "_is_verysafe testing $path\n" if $DEBUG;
735 return 1 if $^O eq 'VMS'; # owner delete control at file level
736
737 my $err_ref = shift;
738
739 # Should Get the value of _PC_CHOWN_RESTRICTED if it is defined
740 # and If it is not there do the extensive test
741 local($@);
742 my $chown_restricted;
743 $chown_restricted = &POSIX::_PC_CHOWN_RESTRICTED()
744 if eval { &POSIX::_PC_CHOWN_RESTRICTED(); 1};
745
746 # If chown_resticted is set to some value we should test it
747 if (defined $chown_restricted) {
748
749 # Return if the current directory is safe
750 return _is_safe($path,$err_ref) if POSIX::sysconf( $chown_restricted );
751
752 }
753
754 # To reach this point either, the _PC_CHOWN_RESTRICTED symbol
755 # was not available or the symbol was there but chown giveaway
756 # is allowed. Either way, we now have to test the entire tree for
757 # safety.
758
759 # Convert path to an absolute directory if required
760 unless (File::Spec->file_name_is_absolute($path)) {
761 $path = File::Spec->rel2abs($path);
762 }
763
764 # Split directory into components - assume no file
765 my ($volume, $directories, undef) = File::Spec->splitpath( $path, 1);
766
767 # Slightly less efficient than having a function in File::Spec
768 # to chop off the end of a directory or even a function that
769 # can handle ../ in a directory tree
770 # Sometimes splitdir() returns a blank at the end
771 # so we will probably check the bottom directory twice in some cases
772 my @dirs = File::Spec->splitdir($directories);
773
774 # Concatenate one less directory each time around
775 foreach my $pos (0.. $#dirs) {
776 # Get a directory name
777 my $dir = File::Spec->catpath($volume,
778 File::Spec->catdir(@dirs[0.. $#dirs - $pos]),
779 ''
780 );
781
782 print "TESTING DIR $dir\n" if $DEBUG;
783
784 # Check the directory
785 return 0 unless _is_safe($dir,$err_ref);
786
787 }
788
789 return 1;
790}
791
792# internal routine to determine whether unlink works on this
793# platform for files that are currently open.
794# Returns true if we can, false otherwise.
795
796# Currently WinNT, OS/2 and VMS can not unlink an opened file
797# On VMS this is because the O_EXCL flag is used to open the
798# temporary file. Currently I do not know enough about the issues
799# on VMS to decide whether O_EXCL is a requirement.
800
801sub _can_unlink_opened_file {
802
803 if (grep $^O eq $_, qw/MSWin32 os2 VMS dos MacOS haiku/) {
804 return 0;
805 } else {
806 return 1;
807 }
808
809}
810
811# internal routine to decide which security levels are allowed
812# see safe_level() for more information on this
813
814# Controls whether the supplied security level is allowed
815
816# $cando = _can_do_level( $level )
817
818sub _can_do_level {
819
820 # Get security level
821 my $level = shift;
822
823 # Always have to be able to do STANDARD
824 return 1 if $level == STANDARD;
825
826 # Currently, the systems that can do HIGH or MEDIUM are identical
827 if ( $^O eq 'MSWin32' || $^O eq 'os2' || $^O eq 'cygwin' || $^O eq 'dos' || $^O eq 'MacOS' || $^O eq 'mpeix') {
828 return 0;
829 } else {
830 return 1;
831 }
832
833}
834
835# This routine sets up a deferred unlinking of a specified
836# filename and filehandle. It is used in the following cases:
837# - Called by unlink0 if an opened file can not be unlinked
838# - Called by tempfile() if files are to be removed on shutdown
839# - Called by tempdir() if directories are to be removed on shutdown
840
841# Arguments:
842# _deferred_unlink( $fh, $fname, $isdir );
843#
844# - filehandle (so that it can be explicitly closed if open
845# - filename (the thing we want to remove)
846# - isdir (flag to indicate that we are being given a directory)
847# [and hence no filehandle]
848
849# Status is not referred to since all the magic is done with an END block
850
851{
852 # Will set up two lexical variables to contain all the files to be
853 # removed. One array for files, another for directories They will
854 # only exist in this block.
855
856 # This means we only have to set up a single END block to remove
857 # all files.
858
859 # in order to prevent child processes inadvertently deleting the parent
860 # temp files we use a hash to store the temp files and directories
861 # created by a particular process id.
862
863 # %files_to_unlink contains values that are references to an array of
864 # array references containing the filehandle and filename associated with
865 # the temp file.
8661300ns my (%files_to_unlink, %dirs_to_unlink);
867
868 # Set up an end block to use these arrays
869
# spent 107µs (40+67) within File::Temp::END which was called: # once (40µs+67µs) by main::RUNTIME at line 0 of /home/hejohns/documentsNoSync/22f/490/gradescope-utils/bin/split.pl
END {
870127µs local($., $@, $!, $^E, $?);
871111µs167µs cleanup(at_exit => 1);
# spent 67µs making 1 call to File::Temp::cleanup
872 }
873
874 # Cleanup function. Always triggered on END (with at_exit => 1) but
875 # can be invoked manually.
876
# spent 67µs (66+1) within File::Temp::cleanup which was called: # once (66µs+1µs) by File::Temp::END at line 871
sub cleanup {
877113µs my %h = @_;
87811µs my $at_exit = delete $h{at_exit};
8791400ns $at_exit = 0 if not defined $at_exit;
880332µs11µs { my @k = sort keys %h; die "unrecognized parameters: @k" if @k }
# spent 1µs making 1 call to File::Temp::CORE:sort
881
88217µs if (!$KEEP_ALL) {
883 # Files
884 my @files = (exists $files_to_unlink{$$} ?
88513µs @{ $files_to_unlink{$$} } : () );
88616µs foreach my $file (@files) {
887 # close the filehandle without checking its state
888 # in order to make real sure that this is closed
889 # if its already closed then I don't care about the answer
890 # probably a better way to do this
891 close($file->[0]); # file handle is [0]
892
893 if (-f $file->[1]) { # file name is [1]
894 _force_writable( $file->[1] ); # for windows
895 unlink $file->[1] or warn "Error removing ".$file->[1];
896 }
897 }
898 # Dirs
899 my @dirs = (exists $dirs_to_unlink{$$} ?
90012µs @{ $dirs_to_unlink{$$} } : () );
9011400ns my ($cwd, $cwd_to_remove);
9021500ns foreach my $dir (@dirs) {
903 if (-d $dir) {
904 # Some versions of rmtree will abort if you attempt to remove
905 # the directory you are sitting in. For automatic cleanup
906 # at program exit, we avoid this by chdir()ing out of the way
907 # first. If not at program exit, it's best not to mess with the
908 # current directory, so just let it fail with a warning.
909 if ($at_exit) {
910 $cwd = Cwd::abs_path(File::Spec->curdir) if not defined $cwd;
911 my $abs = Cwd::abs_path($dir);
912 if ($abs eq $cwd) {
913 $cwd_to_remove = $dir;
914 next;
915 }
916 }
917 eval { rmtree($dir, $DEBUG, 0); };
918 warn $@ if ($@ && $^W);
919 }
920 }
921
9221600ns if (defined $cwd_to_remove) {
923 # We do need to clean up the current directory, and everything
924 # else is done, so get out of there and remove it.
925 chdir $cwd_to_remove or die "cannot chdir to $cwd_to_remove: $!";
926 my $updir = File::Spec->updir;
927 chdir $updir or die "cannot chdir to $updir: $!";
928 eval { rmtree($cwd_to_remove, $DEBUG, 0); };
929 warn $@ if ($@ && $^W);
930 }
931
932 # clear the arrays
933 @{ $files_to_unlink{$$} } = ()
93412µs if exists $files_to_unlink{$$};
935 @{ $dirs_to_unlink{$$} } = ()
93612µs if exists $dirs_to_unlink{$$};
937 }
938 }
939
940 # This is the sub called to register a file for deferred unlinking
941 # This could simply store the input parameters and defer everything
942 # until the END block. For now we do a bit of checking at this
943 # point in order to make sure that (1) we have a file/dir to delete
944 # and (2) we have been called with the correct arguments.
945 sub _deferred_unlink {
946
947 croak 'Usage: _deferred_unlink($fh, $fname, $isdir)'
948 unless scalar(@_) == 3;
949
950 my ($fh, $fname, $isdir) = @_;
951
952 warn "Setting up deferred removal of $fname\n"
953 if $DEBUG;
954
955 # make sure we save the absolute path for later cleanup
956 # OK to untaint because we only ever use this internally
957 # as a file path, never interpolating into the shell
958 $fname = Cwd::abs_path($fname);
959 ($fname) = $fname =~ /^(.*)$/;
960
961 # If we have a directory, check that it is a directory
962 if ($isdir) {
963
964 if (-d $fname) {
965
966 # Directory exists so store it
967 # first on VMS turn []foo into [.foo] for rmtree
968 $fname = VMS::Filespec::vmspath($fname) if $^O eq 'VMS';
969 $dirs_to_unlink{$$} = []
970 unless exists $dirs_to_unlink{$$};
971 push (@{ $dirs_to_unlink{$$} }, $fname);
972
973 } else {
974 carp "Request to remove directory $fname could not be completed since it does not exist!\n" if $^W;
975 }
976
977 } else {
978
979 if (-f $fname) {
980
981 # file exists so store handle and name for later removal
982 $files_to_unlink{$$} = []
983 unless exists $files_to_unlink{$$};
984 push(@{ $files_to_unlink{$$} }, [$fh, $fname]);
985
986 } else {
987 carp "Request to remove file $fname could not be completed since it is not there!\n" if $^W;
988 }
989
990 }
991
992 }
993
994}
995
996# normalize argument keys to upper case and do consistent handling
997# of leading template vs TEMPLATE
9981200ns
# spent 1.21s within File::Temp::_parse_args which was called 266070 times, avg 5µs/call: # 133035 times (1.01s+0s) by File::Temp::new at line 1073, avg 8µs/call # 133035 times (202ms+0s) by File::Temp::tempfile at line 1402, avg 2µs/call
sub _parse_args {
999266070325ms my $leading_template = (scalar(@_) % 2 == 1 ? shift(@_) : '' );
100026607081.9ms my %args = @_;
1001266070311ms %args = map +(uc($_) => $args{$_}), keys %args;
1002
1003 # template (store it in an array so that it will
1004 # disappear from the arg list of tempfile)
1005 my @template = (
1006 exists $args{TEMPLATE} ? $args{TEMPLATE} :
1007266070131ms $leading_template ? $leading_template : ()
1008 );
100926607061.9ms delete $args{TEMPLATE};
1010
1011266070816ms return( \@template, \%args );
1012}
1013
1014#pod =head1 OBJECT-ORIENTED INTERFACE
1015#pod
1016#pod This is the primary interface for interacting with
1017#pod C<File::Temp>. Using the OO interface a temporary file can be created
1018#pod when the object is constructed and the file can be removed when the
1019#pod object is no longer required.
1020#pod
1021#pod Note that there is no method to obtain the filehandle from the
1022#pod C<File::Temp> object. The object itself acts as a filehandle. The object
1023#pod isa C<IO::Handle> and isa C<IO::Seekable> so all those methods are
1024#pod available.
1025#pod
1026#pod Also, the object is configured such that it stringifies to the name of the
1027#pod temporary file and so can be compared to a filename directly. It numifies
1028#pod to the C<refaddr> the same as other handles and so can be compared to other
1029#pod handles with C<==>.
1030#pod
1031#pod $fh eq $filename # as a string
1032#pod $fh != \*STDOUT # as a number
1033#pod
1034#pod Available since 0.14.
1035#pod
1036#pod =over 4
1037#pod
1038#pod =item B<new>
1039#pod
1040#pod Create a temporary file object.
1041#pod
1042#pod my $tmp = File::Temp->new();
1043#pod
1044#pod by default the object is constructed as if C<tempfile>
1045#pod was called without options, but with the additional behaviour
1046#pod that the temporary file is removed by the object destructor
1047#pod if UNLINK is set to true (the default).
1048#pod
1049#pod Supported arguments are the same as for C<tempfile>: UNLINK
1050#pod (defaulting to true), DIR, EXLOCK, PERMS and SUFFIX.
1051#pod Additionally, the filename
1052#pod template is specified using the TEMPLATE option. The OPEN option
1053#pod is not supported (the file is always opened).
1054#pod
1055#pod $tmp = File::Temp->new( TEMPLATE => 'tempXXXXX',
1056#pod DIR => 'mydir',
1057#pod SUFFIX => '.dat');
1058#pod
1059#pod Arguments are case insensitive.
1060#pod
1061#pod Can call croak() if an error occurs.
1062#pod
1063#pod Available since 0.14.
1064#pod
1065#pod TEMPLATE available since 0.23
1066#pod
1067#pod =cut
1068
1069
# spent 42.8s (2.79+40.0) within File::Temp::new which was called 133035 times, avg 321µs/call: # 133035 times (2.79s+40.0s) by Capture::Tiny::_capture_tee at line 360 of Capture/Tiny.pm, avg 321µs/call
sub new {
107013303550.1ms my $proto = shift;
107113303552.8ms my $class = ref($proto) || $proto;
1072
1073133035271ms1330351.01s my ($maybe_template, $args) = _parse_args(@_);
# spent 1.01s making 133035 calls to File::Temp::_parse_args, avg 8µs/call
1074
1075 # see if they are unlinking (defaulting to yes)
107613303573.8ms my $unlink = (exists $args->{UNLINK} ? $args->{UNLINK} : 1 );
107713303533.0ms delete $args->{UNLINK};
1078
1079 # Protect OPEN
108013303518.5ms delete $args->{OPEN};
1081
1082 # Open the file and retain file handle and file name
1083133035245ms13303538.6s my ($fh, $path) = tempfile( @$maybe_template, %$args );
# spent 38.6s making 133035 calls to File::Temp::tempfile, avg 290µs/call
1084
108513303531.3ms print "Tmp: $fh - $path\n" if $DEBUG;
1086
1087 # Store the filename in the scalar slot
108813303569.9ms ${*$fh} = $path;
1089
1090 # Cache the filename by pid so that the destructor can decide whether to remove it
1091133035530ms $FILES_CREATED_BY_OBJECT{$$}{$path} = 1;
1092
1093 # Store unlink information in hash slot (plus other constructor info)
109413303592.3ms %{*$fh} = %$args;
1095
1096 # create the object
1097133035140ms bless $fh, $class;
1098
1099 # final method-based configuration
1100133035223ms133035328ms $fh->unlink_on_destroy( $unlink );
# spent 328ms making 133035 calls to File::Temp::unlink_on_destroy, avg 2µs/call
1101
1102133035395ms return $fh;
1103}
1104
1105#pod =item B<newdir>
1106#pod
1107#pod Create a temporary directory using an object oriented interface.
1108#pod
1109#pod $dir = File::Temp->newdir();
1110#pod
1111#pod By default the directory is deleted when the object goes out of scope.
1112#pod
1113#pod Supports the same options as the C<tempdir> function. Note that directories
1114#pod created with this method default to CLEANUP => 1.
1115#pod
1116#pod $dir = File::Temp->newdir( $template, %options );
1117#pod
1118#pod A template may be specified either with a leading template or
1119#pod with a TEMPLATE argument.
1120#pod
1121#pod Available since 0.19.
1122#pod
1123#pod TEMPLATE available since 0.23.
1124#pod
1125#pod =cut
1126
1127sub newdir {
1128 my $self = shift;
1129
1130 my ($maybe_template, $args) = _parse_args(@_);
1131
1132 # handle CLEANUP without passing CLEANUP to tempdir
1133 my $cleanup = (exists $args->{CLEANUP} ? $args->{CLEANUP} : 1 );
1134 delete $args->{CLEANUP};
1135
1136 my $tempdir = tempdir( @$maybe_template, %$args);
1137
1138 # get a safe absolute path for cleanup, just like
1139 # happens in _deferred_unlink
1140 my $real_dir = Cwd::abs_path( $tempdir );
1141 ($real_dir) = $real_dir =~ /^(.*)$/;
1142
1143 return bless { DIRNAME => $tempdir,
1144 REALNAME => $real_dir,
1145 CLEANUP => $cleanup,
1146 LAUNCHPID => $$,
1147 }, "File::Temp::Dir";
1148}
1149
1150#pod =item B<filename>
1151#pod
1152#pod Return the name of the temporary file associated with this object
1153#pod (if the object was created using the "new" constructor).
1154#pod
1155#pod $filename = $tmp->filename;
1156#pod
1157#pod This method is called automatically when the object is used as
1158#pod a string.
1159#pod
1160#pod Current API available since 0.14
1161#pod
1162#pod =cut
1163
1164
# spent 298ms within File::Temp::filename which was called 133035 times, avg 2µs/call: # 133035 times (298ms+0s) by File::Temp::DESTROY at line 1242, avg 2µs/call
sub filename {
116513303533.5ms my $self = shift;
1166133035627ms return ${*$self};
1167}
1168
1169sub STRINGIFY {
1170 my $self = shift;
1171 return $self->filename;
1172}
1173
1174# For reference, can't use '0+'=>\&Scalar::Util::refaddr directly because
1175# refaddr() demands one parameter only, whereas overload.pm calls with three
1176# even for unary operations like '0+'.
1177sub NUMIFY {
1178 return refaddr($_[0]);
1179}
1180
1181#pod =item B<dirname>
1182#pod
1183#pod Return the name of the temporary directory associated with this
1184#pod object (if the object was created using the "newdir" constructor).
1185#pod
1186#pod $dirname = $tmpdir->dirname;
1187#pod
1188#pod This method is called automatically when the object is used in string context.
1189#pod
1190#pod =item B<unlink_on_destroy>
1191#pod
1192#pod Control whether the file is unlinked when the object goes out of scope.
1193#pod The file is removed if this value is true and $KEEP_ALL is not.
1194#pod
1195#pod $fh->unlink_on_destroy( 1 );
1196#pod
1197#pod Default is for the file to be removed.
1198#pod
1199#pod Current API available since 0.15
1200#pod
1201#pod =cut
1202
1203
# spent 328ms within File::Temp::unlink_on_destroy which was called 133035 times, avg 2µs/call: # 133035 times (328ms+0s) by File::Temp::new at line 1100, avg 2µs/call
sub unlink_on_destroy {
120413303535.8ms my $self = shift;
1205133035133ms if (@_) {
1206 ${*$self}{UNLINK} = shift;
1207 }
1208133035428ms return ${*$self}{UNLINK};
1209}
1210
1211#pod =item B<DESTROY>
1212#pod
1213#pod When the object goes out of scope, the destructor is called. This
1214#pod destructor will attempt to unlink the file (using L<unlink1|"unlink1">)
1215#pod if the constructor was called with UNLINK set to 1 (the default state
1216#pod if UNLINK is not specified).
1217#pod
1218#pod No error is given if the unlink fails.
1219#pod
1220#pod If the object has been passed to a child process during a fork, the
1221#pod file will be deleted when the object goes out of scope in the parent.
1222#pod
1223#pod For a temporary directory object the directory will be removed unless
1224#pod the CLEANUP argument was used in the constructor (and set to false) or
1225#pod C<unlink_on_destroy> was modified after creation. Note that if a temp
1226#pod directory is your current directory, it cannot be removed - a warning
1227#pod will be given in this case. C<chdir()> out of the directory before
1228#pod letting the object go out of scope.
1229#pod
1230#pod If the global variable $KEEP_ALL is true, the file or directory
1231#pod will not be removed.
1232#pod
1233#pod =cut
1234
1235
# spent 30.3s (5.22+25.1) within File::Temp::DESTROY which was called 133035 times, avg 228µs/call: # 133035 times (5.22s+25.1s) by Capture::Tiny::_capture_tee at line 417 of Capture/Tiny.pm, avg 228µs/call
sub DESTROY {
12361330352.11s local($., $@, $!, $^E, $?);
123713303539.7ms my $self = shift;
1238
1239 # Make sure we always remove the file from the global hash
1240 # on destruction. This prevents the hash from growing uncontrollably
1241 # and post-destruction there is no reason to know about the file.
1242133035279ms133035298ms my $file = $self->filename;
# spent 298ms making 133035 calls to File::Temp::filename, avg 2µs/call
124313303518.7ms my $was_created_by_proc;
1244133035304ms if (exists $FILES_CREATED_BY_OBJECT{$$}{$file}) {
124513303534.6ms $was_created_by_proc = 1;
1246133035604ms delete $FILES_CREATED_BY_OBJECT{$$}{$file};
1247 }
1248
12491330351.07s if (${*$self}{UNLINK} && !$KEEP_ALL) {
125013303549.6ms print "# ---------> Unlinking $self\n" if $DEBUG;
1251
1252 # only delete if this process created it
125313303525.3ms return unless $was_created_by_proc;
1254
1255 # The unlink1 may fail if the file has been closed
1256 # by the caller. This leaves us with the decision
1257 # of whether to refuse to remove the file or simply
1258 # do an unlink without test. Seems to be silly
1259 # to do this when we are trying to be careful
1260 # about security
1261133035249ms1330354.45s _force_writable( $file ); # for windows
# spent 4.45s making 133035 calls to File::Temp::_force_writable, avg 33µs/call
1262133035282ms13303520.3s unlink1( $self, $file )
# spent 20.3s making 133035 calls to File::Temp::unlink1, avg 153µs/call
1263 or unlink($file);
1264 }
1265}
1266
1267#pod =back
1268#pod
1269#pod =head1 FUNCTIONS
1270#pod
1271#pod This section describes the recommended interface for generating
1272#pod temporary files and directories.
1273#pod
1274#pod =over 4
1275#pod
1276#pod =item B<tempfile>
1277#pod
1278#pod This is the basic function to generate temporary files.
1279#pod The behaviour of the file can be changed using various options:
1280#pod
1281#pod $fh = tempfile();
1282#pod ($fh, $filename) = tempfile();
1283#pod
1284#pod Create a temporary file in the directory specified for temporary
1285#pod files, as specified by the tmpdir() function in L<File::Spec>.
1286#pod
1287#pod ($fh, $filename) = tempfile($template);
1288#pod
1289#pod Create a temporary file in the current directory using the supplied
1290#pod template. Trailing `X' characters are replaced with random letters to
1291#pod generate the filename. At least four `X' characters must be present
1292#pod at the end of the template.
1293#pod
1294#pod ($fh, $filename) = tempfile($template, SUFFIX => $suffix)
1295#pod
1296#pod Same as previously, except that a suffix is added to the template
1297#pod after the `X' translation. Useful for ensuring that a temporary
1298#pod filename has a particular extension when needed by other applications.
1299#pod But see the WARNING at the end.
1300#pod
1301#pod ($fh, $filename) = tempfile($template, DIR => $dir);
1302#pod
1303#pod Translates the template as before except that a directory name
1304#pod is specified.
1305#pod
1306#pod ($fh, $filename) = tempfile($template, TMPDIR => 1);
1307#pod
1308#pod Equivalent to specifying a DIR of "File::Spec->tmpdir", writing the file
1309#pod into the same temporary directory as would be used if no template was
1310#pod specified at all.
1311#pod
1312#pod ($fh, $filename) = tempfile($template, UNLINK => 1);
1313#pod
1314#pod Return the filename and filehandle as before except that the file is
1315#pod automatically removed when the program exits (dependent on
1316#pod $KEEP_ALL). Default is for the file to be removed if a file handle is
1317#pod requested and to be kept if the filename is requested. In a scalar
1318#pod context (where no filename is returned) the file is always deleted
1319#pod either (depending on the operating system) on exit or when it is
1320#pod closed (unless $KEEP_ALL is true when the temp file is created).
1321#pod
1322#pod Use the object-oriented interface if fine-grained control of when
1323#pod a file is removed is required.
1324#pod
1325#pod If the template is not specified, a template is always
1326#pod automatically generated. This temporary file is placed in tmpdir()
1327#pod (L<File::Spec>) unless a directory is specified explicitly with the
1328#pod DIR option.
1329#pod
1330#pod $fh = tempfile( DIR => $dir );
1331#pod
1332#pod If called in scalar context, only the filehandle is returned and the
1333#pod file will automatically be deleted when closed on operating systems
1334#pod that support this (see the description of tmpfile() elsewhere in this
1335#pod document). This is the preferred mode of operation, as if you only
1336#pod have a filehandle, you can never create a race condition by fumbling
1337#pod with the filename. On systems that can not unlink an open file or can
1338#pod not mark a file as temporary when it is opened (for example, Windows
1339#pod NT uses the C<O_TEMPORARY> flag) the file is marked for deletion when
1340#pod the program ends (equivalent to setting UNLINK to 1). The C<UNLINK>
1341#pod flag is ignored if present.
1342#pod
1343#pod (undef, $filename) = tempfile($template, OPEN => 0);
1344#pod
1345#pod This will return the filename based on the template but
1346#pod will not open this file. Cannot be used in conjunction with
1347#pod UNLINK set to true. Default is to always open the file
1348#pod to protect from possible race conditions. A warning is issued
1349#pod if warnings are turned on. Consider using the tmpnam()
1350#pod and mktemp() functions described elsewhere in this document
1351#pod if opening the file is not required.
1352#pod
1353#pod To open the temporary filehandle with O_EXLOCK (open with exclusive
1354#pod file lock) use C<< EXLOCK=>1 >>. This is supported only by some
1355#pod operating systems (most notably BSD derived systems). By default
1356#pod EXLOCK will be false. Former C<File::Temp> versions set EXLOCK to
1357#pod true, so to be sure to get an unlocked filehandle also with older
1358#pod versions, explicitly set C<< EXLOCK=>0 >>.
1359#pod
1360#pod ($fh, $filename) = tempfile($template, EXLOCK => 1);
1361#pod
1362#pod By default, the temp file is created with 0600 file permissions.
1363#pod Use C<PERMS> to change this:
1364#pod
1365#pod ($fh, $filename) = tempfile($template, PERMS => 0666);
1366#pod
1367#pod Options can be combined as required.
1368#pod
1369#pod Will croak() if there is an error.
1370#pod
1371#pod Available since 0.05.
1372#pod
1373#pod UNLINK flag available since 0.10.
1374#pod
1375#pod TMPDIR flag available since 0.19.
1376#pod
1377#pod EXLOCK flag available since 0.19.
1378#pod
1379#pod PERMS flag available since 0.2310.
1380#pod
1381#pod =cut
1382
1383
# spent 38.6s (4.54+34.1) within File::Temp::tempfile which was called 133035 times, avg 290µs/call: # 133035 times (4.54s+34.1s) by File::Temp::new at line 1083, avg 290µs/call
sub tempfile {
138413303546.8ms if ( @_ && $_[0] eq 'File::Temp' ) {
1385 croak "'tempfile' can't be called as a method";
1386 }
1387 # Can not check for argument count since we can have any
1388 # number of args
1389
1390 # Default options
13911330351.26s my %options = (
1392 "DIR" => undef, # Directory prefix
1393 "SUFFIX" => '', # Template suffix
1394 "UNLINK" => 0, # Do not unlink file on exit
1395 "OPEN" => 1, # Open file
1396 "TMPDIR" => 0, # Place tempfile in tempdir if template specified
1397 "EXLOCK" => 0, # Open file with O_EXLOCK
1398 "PERMS" => undef, # File permissions
1399 );
1400
1401 # Check to see whether we have an odd or even number of arguments
140213303598.5ms133035202ms my ($maybe_template, $args) = _parse_args(@_);
# spent 202ms making 133035 calls to File::Temp::_parse_args, avg 2µs/call
140313303566.7ms my $template = @$maybe_template ? $maybe_template->[0] : undef;
1404
1405 # Read the options and merge with defaults
1406133035351ms %options = (%options, %$args);
1407
1408 # First decision is whether or not to open the file
140913303556.7ms if (! $options{"OPEN"}) {
1410
1411 warn "tempfile(): temporary filename requested but not opened.\nPossibly unsafe, consider using tempfile() with OPEN set to true\n"
1412 if $^W;
1413
1414 }
1415
141613303557.5ms if ($options{"DIR"} and $^O eq 'VMS') {
1417
1418 # on VMS turn []foo into [.foo] for concatenation
1419 $options{"DIR"} = VMS::Filespec::vmspath($options{"DIR"});
1420 }
1421
1422 # Construct the template
1423
1424 # Have a choice of trying to work around the mkstemp/mktemp/tmpnam etc
1425 # functions or simply constructing a template and using _gettemp()
1426 # explicitly. Go for the latter
1427
1428 # First generate a template if not defined and prefix the directory
1429 # If no template must prefix the temp directory
1430133035116ms if (defined $template) {
1431 # End up with current directory if neither DIR not TMPDIR are set
1432 if ($options{"DIR"}) {
1433
1434 $template = File::Spec->catfile($options{"DIR"}, $template);
1435
1436 } elsif ($options{TMPDIR}) {
1437
1438 $template = File::Spec->catfile(_wrap_file_spec_tmpdir(), $template );
1439
1440 }
1441
1442 } else {
1443
144413303555.0ms if ($options{"DIR"}) {
1445
1446 $template = File::Spec->catfile($options{"DIR"}, TEMPXXX);
1447
1448 } else {
1449
14501330352.60s6651755.71s $template = File::Spec->catfile(_wrap_file_spec_tmpdir(), TEMPXXX);
# spent 3.07s making 133035 calls to File::Temp::_wrap_file_spec_tmpdir, avg 23µs/call # spent 1.91s making 133035 calls to File::Spec::Unix::catfile, avg 14µs/call # spent 562ms making 133035 calls to File::Spec::Unix::catdir, avg 4µs/call # spent 175ms making 266070 calls to File::Spec::Unix::canonpath, avg 657ns/call
1451
1452 }
1453
1454 }
1455
1456 # Now add a suffix
145713303570.4ms $template .= $options{"SUFFIX"};
1458
1459 # Determine whether we should tell _gettemp to unlink the file
1460 # On unix this is irrelevant and can be worked out after the file is
1461 # opened (simply by unlinking the open filehandle). On Windows or VMS
1462 # we have to indicate temporary-ness when we open the file. In general
1463 # we only want a true temporary file if we are returning just the
1464 # filehandle - if the user wants the filename they probably do not
1465 # want the file to disappear as soon as they close it (which may be
1466 # important if they want a child process to use the file)
1467 # For this reason, tie unlink_on_close to the return context regardless
1468 # of OS.
146913303540.9ms my $unlink_on_close = ( wantarray ? 0 : 1);
1470
1471 # Create the file
147213303527.1ms my ($fh, $path, $errstr);
1473 croak "Error in tempfile() using template $template: $errstr"
1474 unless (($fh, $path) = _gettemp($template,
1475 "open" => $options{OPEN},
1476 "mkdir" => 0,
1477 "unlink_on_close" => $unlink_on_close,
1478 "suffixlen" => length($options{SUFFIX}),
1479 "ErrStr" => \$errstr,
1480 "use_exlock" => $options{EXLOCK},
1481 "file_permissions" => $options{PERMS},
1482133035474ms13303528.9s ) );
# spent 28.9s making 133035 calls to File::Temp::_gettemp, avg 217µs/call
1483
1484 # Set up an exit handler that can do whatever is right for the
1485 # system. This removes files at exit when requested explicitly or when
1486 # system is asked to unlink_on_close but is unable to do so because
1487 # of OS limitations.
1488 # The latter should be achieved by using a tied filehandle.
1489 # Do not check return status since this is all done with END blocks.
149013303565.5ms _deferred_unlink($fh, $path, 0) if $options{"UNLINK"};
1491
1492 # Return
1493133035621ms if (wantarray()) {
1494
1495 if ($options{'OPEN'}) {
1496 return ($fh, $path);
1497 } else {
1498 return (undef, $path);
1499 }
1500
1501 } else {
1502
1503 # Unlink the file. It is up to unlink0 to decide what to do with
1504 # this (whether to unlink now or to defer until later)
1505 unlink0($fh, $path) or croak "Error unlinking file $path using unlink0";
1506
1507 # Return just the filehandle.
1508 return $fh;
1509 }
1510
1511}
1512
1513# On Windows under taint mode, File::Spec could suggest "C:\" as a tempdir
1514# which might not be writable. If that is the case, we fallback to a
1515# user directory. See https://rt.cpan.org/Ticket/Display.html?id=60340
1516
1517{
15181400ns my ($alt_tmpdir, $checked);
1519
1520
# spent 3.07s (958ms+2.11) within File::Temp::_wrap_file_spec_tmpdir which was called 133035 times, avg 23µs/call: # 133035 times (958ms+2.11s) by File::Temp::tempfile at line 1450, avg 23µs/call
sub _wrap_file_spec_tmpdir {
15211330351.28s1330352.11s return File::Spec->tmpdir unless $^O eq "MSWin32" && ${^TAINT};
# spent 2.11s making 133035 calls to File::Spec::Unix::tmpdir, avg 16µs/call
1522
1523 if ( $checked ) {
1524 return $alt_tmpdir ? $alt_tmpdir : File::Spec->tmpdir;
1525 }
1526
1527 # probe what File::Spec gives and find a fallback
1528 my $xxpath = _replace_XX( "X" x 10, 0 );
1529
1530 # First, see if File::Spec->tmpdir is writable
1531 my $tmpdir = File::Spec->tmpdir;
1532 my $testpath = File::Spec->catdir( $tmpdir, $xxpath );
1533 if (mkdir( $testpath, 0700) ) {
1534 $checked = 1;
1535 rmdir $testpath;
1536 return $tmpdir;
1537 }
1538
1539 # Next, see if CSIDL_LOCAL_APPDATA is writable
1540 require Win32;
1541 my $local_app = File::Spec->catdir(
1542 Win32::GetFolderPath( Win32::CSIDL_LOCAL_APPDATA() ), 'Temp'
1543 );
1544 $testpath = File::Spec->catdir( $local_app, $xxpath );
1545 if ( -e $local_app or mkdir( $local_app, 0700 ) ) {
1546 if (mkdir( $testpath, 0700) ) {
1547 $checked = 1;
1548 rmdir $testpath;
1549 return $alt_tmpdir = $local_app;
1550 }
1551 }
1552
1553 # Can't find something writable
1554 croak << "HERE";
1555Couldn't find a writable temp directory in taint mode. Tried:
1556 $tmpdir
1557 $local_app
1558
1559Try setting and untainting the TMPDIR environment variable.
1560HERE
1561
1562 }
1563}
1564
1565#pod =item B<tempdir>
1566#pod
1567#pod This is the recommended interface for creation of temporary
1568#pod directories. By default the directory will not be removed on exit
1569#pod (that is, it won't be temporary; this behaviour can not be changed
1570#pod because of issues with backwards compatibility). To enable removal
1571#pod either use the CLEANUP option which will trigger removal on program
1572#pod exit, or consider using the "newdir" method in the object interface which
1573#pod will allow the directory to be cleaned up when the object goes out of
1574#pod scope.
1575#pod
1576#pod The behaviour of the function depends on the arguments:
1577#pod
1578#pod $tempdir = tempdir();
1579#pod
1580#pod Create a directory in tmpdir() (see L<File::Spec|File::Spec>).
1581#pod
1582#pod $tempdir = tempdir( $template );
1583#pod
1584#pod Create a directory from the supplied template. This template is
1585#pod similar to that described for tempfile(). `X' characters at the end
1586#pod of the template are replaced with random letters to construct the
1587#pod directory name. At least four `X' characters must be in the template.
1588#pod
1589#pod $tempdir = tempdir ( DIR => $dir );
1590#pod
1591#pod Specifies the directory to use for the temporary directory.
1592#pod The temporary directory name is derived from an internal template.
1593#pod
1594#pod $tempdir = tempdir ( $template, DIR => $dir );
1595#pod
1596#pod Prepend the supplied directory name to the template. The template
1597#pod should not include parent directory specifications itself. Any parent
1598#pod directory specifications are removed from the template before
1599#pod prepending the supplied directory.
1600#pod
1601#pod $tempdir = tempdir ( $template, TMPDIR => 1 );
1602#pod
1603#pod Using the supplied template, create the temporary directory in
1604#pod a standard location for temporary files. Equivalent to doing
1605#pod
1606#pod $tempdir = tempdir ( $template, DIR => File::Spec->tmpdir);
1607#pod
1608#pod but shorter. Parent directory specifications are stripped from the
1609#pod template itself. The C<TMPDIR> option is ignored if C<DIR> is set
1610#pod explicitly. Additionally, C<TMPDIR> is implied if neither a template
1611#pod nor a directory are supplied.
1612#pod
1613#pod $tempdir = tempdir( $template, CLEANUP => 1);
1614#pod
1615#pod Create a temporary directory using the supplied template, but
1616#pod attempt to remove it (and all files inside it) when the program
1617#pod exits. Note that an attempt will be made to remove all files from
1618#pod the directory even if they were not created by this module (otherwise
1619#pod why ask to clean it up?). The directory removal is made with
1620#pod the rmtree() function from the L<File::Path|File::Path> module.
1621#pod Of course, if the template is not specified, the temporary directory
1622#pod will be created in tmpdir() and will also be removed at program exit.
1623#pod
1624#pod Will croak() if there is an error.
1625#pod
1626#pod Current API available since 0.05.
1627#pod
1628#pod =cut
1629
1630# '
1631
163210ssub tempdir {
1633 if ( @_ && $_[0] eq 'File::Temp' ) {
1634 croak "'tempdir' can't be called as a method";
1635 }
1636
1637 # Can not check for argument count since we can have any
1638 # number of args
1639
1640 # Default options
1641 my %options = (
1642 "CLEANUP" => 0, # Remove directory on exit
1643 "DIR" => '', # Root directory
1644 "TMPDIR" => 0, # Use tempdir with template
1645 );
1646
1647 # Check to see whether we have an odd or even number of arguments
1648 my ($maybe_template, $args) = _parse_args(@_);
1649 my $template = @$maybe_template ? $maybe_template->[0] : undef;
1650
1651 # Read the options and merge with defaults
1652 %options = (%options, %$args);
1653
1654 # Modify or generate the template
1655
1656 # Deal with the DIR and TMPDIR options
1657 if (defined $template) {
1658
1659 # Need to strip directory path if using DIR or TMPDIR
1660 if ($options{'TMPDIR'} || $options{'DIR'}) {
1661
1662 # Strip parent directory from the filename
1663 #
1664 # There is no filename at the end
1665 $template = VMS::Filespec::vmspath($template) if $^O eq 'VMS';
1666 my ($volume, $directories, undef) = File::Spec->splitpath( $template, 1);
1667
1668 # Last directory is then our template
1669 $template = (File::Spec->splitdir($directories))[-1];
1670
1671 # Prepend the supplied directory or temp dir
1672 if ($options{"DIR"}) {
1673
1674 $template = File::Spec->catdir($options{"DIR"}, $template);
1675
1676 } elsif ($options{TMPDIR}) {
1677
1678 # Prepend tmpdir
1679 $template = File::Spec->catdir(_wrap_file_spec_tmpdir(), $template);
1680
1681 }
1682
1683 }
1684
1685 } else {
1686
1687 if ($options{"DIR"}) {
1688
1689 $template = File::Spec->catdir($options{"DIR"}, TEMPXXX);
1690
1691 } else {
1692
1693 $template = File::Spec->catdir(_wrap_file_spec_tmpdir(), TEMPXXX);
1694
1695 }
1696
1697 }
1698
1699 # Create the directory
1700 my $tempdir;
1701 my $suffixlen = 0;
1702 if ($^O eq 'VMS') { # dir names can end in delimiters
1703 $template =~ m/([\.\]:>]+)$/;
1704 $suffixlen = length($1);
1705 }
1706 if ( ($^O eq 'MacOS') && (substr($template, -1) eq ':') ) {
1707 # dir name has a trailing ':'
1708 ++$suffixlen;
1709 }
1710
1711 my $errstr;
1712 croak "Error in tempdir() using $template: $errstr"
1713 unless ((undef, $tempdir) = _gettemp($template,
1714 "open" => 0,
1715 "mkdir"=> 1 ,
1716 "suffixlen" => $suffixlen,
1717 "ErrStr" => \$errstr,
1718 ) );
1719
1720 # Install exit handler; must be dynamic to get lexical
1721 if ( $options{'CLEANUP'} && -d $tempdir) {
1722 _deferred_unlink(undef, $tempdir, 1);
1723 }
1724
1725 # Return the dir name
1726 return $tempdir;
1727
1728}
1729
1730#pod =back
1731#pod
1732#pod =head1 MKTEMP FUNCTIONS
1733#pod
1734#pod The following functions are Perl implementations of the
1735#pod mktemp() family of temp file generation system calls.
1736#pod
1737#pod =over 4
1738#pod
1739#pod =item B<mkstemp>
1740#pod
1741#pod Given a template, returns a filehandle to the temporary file and the name
1742#pod of the file.
1743#pod
1744#pod ($fh, $name) = mkstemp( $template );
1745#pod
1746#pod In scalar context, just the filehandle is returned.
1747#pod
1748#pod The template may be any filename with some number of X's appended
1749#pod to it, for example F</tmp/temp.XXXX>. The trailing X's are replaced
1750#pod with unique alphanumeric combinations.
1751#pod
1752#pod Will croak() if there is an error.
1753#pod
1754#pod Current API available since 0.05.
1755#pod
1756#pod =cut
1757
1758sub mkstemp {
1759
1760 croak "Usage: mkstemp(template)"
1761 if scalar(@_) != 1;
1762
1763 my $template = shift;
1764
1765 my ($fh, $path, $errstr);
1766 croak "Error in mkstemp using $template: $errstr"
1767 unless (($fh, $path) = _gettemp($template,
1768 "open" => 1,
1769 "mkdir"=> 0 ,
1770 "suffixlen" => 0,
1771 "ErrStr" => \$errstr,
1772 ) );
1773
1774 if (wantarray()) {
1775 return ($fh, $path);
1776 } else {
1777 return $fh;
1778 }
1779
1780}
1781
1782#pod =item B<mkstemps>
1783#pod
1784#pod Similar to mkstemp(), except that an extra argument can be supplied
1785#pod with a suffix to be appended to the template.
1786#pod
1787#pod ($fh, $name) = mkstemps( $template, $suffix );
1788#pod
1789#pod For example a template of C<testXXXXXX> and suffix of C<.dat>
1790#pod would generate a file similar to F<testhGji_w.dat>.
1791#pod
1792#pod Returns just the filehandle alone when called in scalar context.
1793#pod
1794#pod Will croak() if there is an error.
1795#pod
1796#pod Current API available since 0.05.
1797#pod
1798#pod =cut
1799
1800sub mkstemps {
1801
1802 croak "Usage: mkstemps(template, suffix)"
1803 if scalar(@_) != 2;
1804
1805 my $template = shift;
1806 my $suffix = shift;
1807
1808 $template .= $suffix;
1809
1810 my ($fh, $path, $errstr);
1811 croak "Error in mkstemps using $template: $errstr"
1812 unless (($fh, $path) = _gettemp($template,
1813 "open" => 1,
1814 "mkdir"=> 0 ,
1815 "suffixlen" => length($suffix),
1816 "ErrStr" => \$errstr,
1817 ) );
1818
1819 if (wantarray()) {
1820 return ($fh, $path);
1821 } else {
1822 return $fh;
1823 }
1824
1825}
1826
1827#pod =item B<mkdtemp>
1828#pod
1829#pod Create a directory from a template. The template must end in
1830#pod X's that are replaced by the routine.
1831#pod
1832#pod $tmpdir_name = mkdtemp($template);
1833#pod
1834#pod Returns the name of the temporary directory created.
1835#pod
1836#pod Directory must be removed by the caller.
1837#pod
1838#pod Will croak() if there is an error.
1839#pod
1840#pod Current API available since 0.05.
1841#pod
1842#pod =cut
1843
1844#' # for emacs
1845
1846sub mkdtemp {
1847
1848 croak "Usage: mkdtemp(template)"
1849 if scalar(@_) != 1;
1850
1851 my $template = shift;
1852 my $suffixlen = 0;
1853 if ($^O eq 'VMS') { # dir names can end in delimiters
1854 $template =~ m/([\.\]:>]+)$/;
1855 $suffixlen = length($1);
1856 }
1857 if ( ($^O eq 'MacOS') && (substr($template, -1) eq ':') ) {
1858 # dir name has a trailing ':'
1859 ++$suffixlen;
1860 }
1861 my ($junk, $tmpdir, $errstr);
1862 croak "Error creating temp directory from template $template\: $errstr"
1863 unless (($junk, $tmpdir) = _gettemp($template,
1864 "open" => 0,
1865 "mkdir"=> 1 ,
1866 "suffixlen" => $suffixlen,
1867 "ErrStr" => \$errstr,
1868 ) );
1869
1870 return $tmpdir;
1871
1872}
1873
1874#pod =item B<mktemp>
1875#pod
1876#pod Returns a valid temporary filename but does not guarantee
1877#pod that the file will not be opened by someone else.
1878#pod
1879#pod $unopened_file = mktemp($template);
1880#pod
1881#pod Template is the same as that required by mkstemp().
1882#pod
1883#pod Will croak() if there is an error.
1884#pod
1885#pod Current API available since 0.05.
1886#pod
1887#pod =cut
1888
1889sub mktemp {
1890
1891 croak "Usage: mktemp(template)"
1892 if scalar(@_) != 1;
1893
1894 my $template = shift;
1895
1896 my ($tmpname, $junk, $errstr);
1897 croak "Error getting name to temp file from template $template: $errstr"
1898 unless (($junk, $tmpname) = _gettemp($template,
1899 "open" => 0,
1900 "mkdir"=> 0 ,
1901 "suffixlen" => 0,
1902 "ErrStr" => \$errstr,
1903 ) );
1904
1905 return $tmpname;
1906}
1907
1908#pod =back
1909#pod
1910#pod =head1 POSIX FUNCTIONS
1911#pod
1912#pod This section describes the re-implementation of the tmpnam()
1913#pod and tmpfile() functions described in L<POSIX>
1914#pod using the mkstemp() from this module.
1915#pod
1916#pod Unlike the L<POSIX|POSIX> implementations, the directory used
1917#pod for the temporary file is not specified in a system include
1918#pod file (C<P_tmpdir>) but simply depends on the choice of tmpdir()
1919#pod returned by L<File::Spec|File::Spec>. On some implementations this
1920#pod location can be set using the C<TMPDIR> environment variable, which
1921#pod may not be secure.
1922#pod If this is a problem, simply use mkstemp() and specify a template.
1923#pod
1924#pod =over 4
1925#pod
1926#pod =item B<tmpnam>
1927#pod
1928#pod When called in scalar context, returns the full name (including path)
1929#pod of a temporary file (uses mktemp()). The only check is that the file does
1930#pod not already exist, but there is no guarantee that that condition will
1931#pod continue to apply.
1932#pod
1933#pod $file = tmpnam();
1934#pod
1935#pod When called in list context, a filehandle to the open file and
1936#pod a filename are returned. This is achieved by calling mkstemp()
1937#pod after constructing a suitable template.
1938#pod
1939#pod ($fh, $file) = tmpnam();
1940#pod
1941#pod If possible, this form should be used to prevent possible
1942#pod race conditions.
1943#pod
1944#pod See L<File::Spec/tmpdir> for information on the choice of temporary
1945#pod directory for a particular operating system.
1946#pod
1947#pod Will croak() if there is an error.
1948#pod
1949#pod Current API available since 0.05.
1950#pod
1951#pod =cut
1952
1953sub tmpnam {
1954
1955 # Retrieve the temporary directory name
1956 my $tmpdir = _wrap_file_spec_tmpdir();
1957
1958 # XXX I don't know under what circumstances this occurs, -- xdg 2016-04-02
1959 croak "Error temporary directory is not writable"
1960 if $tmpdir eq '';
1961
1962 # Use a ten character template and append to tmpdir
1963 my $template = File::Spec->catfile($tmpdir, TEMPXXX);
1964
1965 if (wantarray() ) {
1966 return mkstemp($template);
1967 } else {
1968 return mktemp($template);
1969 }
1970
1971}
1972
1973#pod =item B<tmpfile>
1974#pod
1975#pod Returns the filehandle of a temporary file.
1976#pod
1977#pod $fh = tmpfile();
1978#pod
1979#pod The file is removed when the filehandle is closed or when the program
1980#pod exits. No access to the filename is provided.
1981#pod
1982#pod If the temporary file can not be created undef is returned.
1983#pod Currently this command will probably not work when the temporary
1984#pod directory is on an NFS file system.
1985#pod
1986#pod Will croak() if there is an error.
1987#pod
1988#pod Available since 0.05.
1989#pod
1990#pod Returning undef if unable to create file added in 0.12.
1991#pod
1992#pod =cut
1993
1994sub tmpfile {
1995
1996 # Simply call tmpnam() in a list context
1997 my ($fh, $file) = tmpnam();
1998
1999 # Make sure file is removed when filehandle is closed
2000 # This will fail on NFS
2001 unlink0($fh, $file)
2002 or return undef;
2003
2004 return $fh;
2005
2006}
2007
2008#pod =back
2009#pod
2010#pod =head1 ADDITIONAL FUNCTIONS
2011#pod
2012#pod These functions are provided for backwards compatibility
2013#pod with common tempfile generation C library functions.
2014#pod
2015#pod They are not exported and must be addressed using the full package
2016#pod name.
2017#pod
2018#pod =over 4
2019#pod
2020#pod =item B<tempnam>
2021#pod
2022#pod Return the name of a temporary file in the specified directory
2023#pod using a prefix. The file is guaranteed not to exist at the time
2024#pod the function was called, but such guarantees are good for one
2025#pod clock tick only. Always use the proper form of C<sysopen>
2026#pod with C<O_CREAT | O_EXCL> if you must open such a filename.
2027#pod
2028#pod $filename = File::Temp::tempnam( $dir, $prefix );
2029#pod
2030#pod Equivalent to running mktemp() with $dir/$prefixXXXXXXXX
2031#pod (using unix file convention as an example)
2032#pod
2033#pod Because this function uses mktemp(), it can suffer from race conditions.
2034#pod
2035#pod Will croak() if there is an error.
2036#pod
2037#pod Current API available since 0.05.
2038#pod
2039#pod =cut
2040
2041sub tempnam {
2042
2043 croak 'Usage tempnam($dir, $prefix)' unless scalar(@_) == 2;
2044
2045 my ($dir, $prefix) = @_;
2046
2047 # Add a string to the prefix
2048 $prefix .= 'XXXXXXXX';
2049
2050 # Concatenate the directory to the file
2051 my $template = File::Spec->catfile($dir, $prefix);
2052
2053 return mktemp($template);
2054
2055}
2056
2057#pod =back
2058#pod
2059#pod =head1 UTILITY FUNCTIONS
2060#pod
2061#pod Useful functions for dealing with the filehandle and filename.
2062#pod
2063#pod =over 4
2064#pod
2065#pod =item B<unlink0>
2066#pod
2067#pod Given an open filehandle and the associated filename, make a safe
2068#pod unlink. This is achieved by first checking that the filename and
2069#pod filehandle initially point to the same file and that the number of
2070#pod links to the file is 1 (all fields returned by stat() are compared).
2071#pod Then the filename is unlinked and the filehandle checked once again to
2072#pod verify that the number of links on that file is now 0. This is the
2073#pod closest you can come to making sure that the filename unlinked was the
2074#pod same as the file whose descriptor you hold.
2075#pod
2076#pod unlink0($fh, $path)
2077#pod or die "Error unlinking file $path safely";
2078#pod
2079#pod Returns false on error but croaks() if there is a security
2080#pod anomaly. The filehandle is not closed since on some occasions this is
2081#pod not required.
2082#pod
2083#pod On some platforms, for example Windows NT, it is not possible to
2084#pod unlink an open file (the file must be closed first). On those
2085#pod platforms, the actual unlinking is deferred until the program ends and
2086#pod good status is returned. A check is still performed to make sure that
2087#pod the filehandle and filename are pointing to the same thing (but not at
2088#pod the time the end block is executed since the deferred removal may not
2089#pod have access to the filehandle).
2090#pod
2091#pod Additionally, on Windows NT not all the fields returned by stat() can
2092#pod be compared. For example, the C<dev> and C<rdev> fields seem to be
2093#pod different. Also, it seems that the size of the file returned by stat()
2094#pod does not always agree, with C<stat(FH)> being more accurate than
2095#pod C<stat(filename)>, presumably because of caching issues even when
2096#pod using autoflush (this is usually overcome by waiting a while after
2097#pod writing to the tempfile before attempting to C<unlink0> it).
2098#pod
2099#pod Finally, on NFS file systems the link count of the file handle does
2100#pod not always go to zero immediately after unlinking. Currently, this
2101#pod command is expected to fail on NFS disks.
2102#pod
2103#pod This function is disabled if the global variable $KEEP_ALL is true
2104#pod and an unlink on open file is supported. If the unlink is to be deferred
2105#pod to the END block, the file is still registered for removal.
2106#pod
2107#pod This function should not be called if you are using the object oriented
2108#pod interface since the it will interfere with the object destructor deleting
2109#pod the file.
2110#pod
2111#pod Available Since 0.05.
2112#pod
2113#pod If can not unlink open file, defer removal until later available since 0.06.
2114#pod
2115#pod =cut
2116
2117sub unlink0 {
2118
2119 croak 'Usage: unlink0(filehandle, filename)'
2120 unless scalar(@_) == 2;
2121
2122 # Read args
2123 my ($fh, $path) = @_;
2124
2125 cmpstat($fh, $path) or return 0;
2126
2127 # attempt remove the file (does not work on some platforms)
2128 if (_can_unlink_opened_file()) {
2129
2130 # return early (Without unlink) if we have been instructed to retain files.
2131 return 1 if $KEEP_ALL;
2132
2133 # XXX: do *not* call this on a directory; possible race
2134 # resulting in recursive removal
2135 croak "unlink0: $path has become a directory!" if -d $path;
2136 unlink($path) or return 0;
2137
2138 # Stat the filehandle
2139 my @fh = stat $fh;
2140
2141 print "Link count = $fh[3] \n" if $DEBUG;
2142
2143 # Make sure that the link count is zero
2144 # - Cygwin provides deferred unlinking, however,
2145 # on Win9x the link count remains 1
2146 # On NFS the link count may still be 1 but we can't know that
2147 # we are on NFS. Since we can't be sure, we'll defer it
2148
2149 return 1 if $fh[3] == 0 || $^O eq 'cygwin';
2150 }
2151 # fall-through if we can't unlink now
2152 _deferred_unlink($fh, $path, 0);
2153 return 1;
2154}
2155
2156#pod =item B<cmpstat>
2157#pod
2158#pod Compare C<stat> of filehandle with C<stat> of provided filename. This
2159#pod can be used to check that the filename and filehandle initially point
2160#pod to the same file and that the number of links to the file is 1 (all
2161#pod fields returned by stat() are compared).
2162#pod
2163#pod cmpstat($fh, $path)
2164#pod or die "Error comparing handle with file";
2165#pod
2166#pod Returns false if the stat information differs or if the link count is
2167#pod greater than 1. Calls croak if there is a security anomaly.
2168#pod
2169#pod On certain platforms, for example Windows, not all the fields returned by stat()
2170#pod can be compared. For example, the C<dev> and C<rdev> fields seem to be
2171#pod different in Windows. Also, it seems that the size of the file
2172#pod returned by stat() does not always agree, with C<stat(FH)> being more
2173#pod accurate than C<stat(filename)>, presumably because of caching issues
2174#pod even when using autoflush (this is usually overcome by waiting a while
2175#pod after writing to the tempfile before attempting to C<unlink0> it).
2176#pod
2177#pod Not exported by default.
2178#pod
2179#pod Current API available since 0.14.
2180#pod
2181#pod =cut
2182
2183
# spent 8.02s (6.45+1.57) within File::Temp::cmpstat which was called 133035 times, avg 60µs/call: # 133035 times (6.45s+1.57s) by File::Temp::unlink1 at line 2285, avg 60µs/call
sub cmpstat {
2184
218513303537.2ms croak 'Usage: cmpstat(filehandle, filename)'
2186 unless scalar(@_) == 2;
2187
2188 # Read args
218913303540.6ms my ($fh, $path) = @_;
2190
219113303528.4ms warn "Comparing stat\n"
2192 if $DEBUG;
2193
2194 # Stat the filehandle - which may be closed if someone has manually
2195 # closed the file. Can not turn off warnings without using $^W
2196 # unless we upgrade to 5.006 minimum requirement
219713303530.0ms my @fh;
2198 {
2199266070881ms local ($^W) = 0;
22001330351.68s133035700ms @fh = stat $fh;
# spent 700ms making 133035 calls to File::Temp::CORE:stat, avg 5µs/call
2201 }
220213303537.4ms return unless @fh;
2203
220413303557.5ms if ($fh[3] > 1 && $^W) {
2205 carp "unlink0: fstat found too many links; SB=@fh" if $^W;
2206 }
2207
2208 # Stat the path
22091330351.07s133035381ms my @path = stat $path;
# spent 381ms making 133035 calls to File::Temp::CORE:stat, avg 3µs/call
2210
221113303530.2ms unless (@path) {
2212 carp "unlink0: $path is gone already" if $^W;
2213 return;
2214 }
2215
2216 # this is no longer a file, but may be a directory, or worse
2217133035899ms133035486ms unless (-f $path) {
# spent 486ms making 133035 calls to File::Temp::CORE:ftfile, avg 4µs/call
2218 confess "panic: $path is no longer a file: SB=@fh";
2219 }
2220
2221 # Do comparison of each member of the array
2222 # On WinNT dev and rdev seem to be different
2223 # depending on whether it is a file or a handle.
2224 # Cannot simply compare all members of the stat return
2225 # Select the ones we can use
2226133035403ms my @okstat = (0..$#fh); # Use all by default
2227133035852ms if ($^O eq 'MSWin32') {
2228 @okstat = (1,2,3,4,5,7,8,9,10);
2229 } elsif ($^O eq 'os2') {
2230 @okstat = (0, 2..$#fh);
2231 } elsif ($^O eq 'VMS') { # device and file ID are sufficient
2232 @okstat = (0, 1);
2233 } elsif ($^O eq 'dos') {
2234 @okstat = (0,2..7,11..$#fh);
2235 } elsif ($^O eq 'mpeix') {
2236 @okstat = (0..4,8..10);
2237 }
2238
2239 # Now compare each entry explicitly by number
2240133035283ms for (@okstat) {
22411729455119ms print "Comparing: $_ : $fh[$_] and $path[$_]\n" if $DEBUG;
2242 # Use eq rather than == since rdev, blksize, and blocks (6, 11,
2243 # and 12) will be '' on platforms that do not support them. This
2244 # is fine since we are only comparing integers.
224517294551.14s unless ($fh[$_] eq $path[$_]) {
2246 warn "Did not match $_ element of stat\n" if $DEBUG;
2247 return 0;
2248 }
2249 }
2250
2251133035676ms return 1;
2252}
2253
2254#pod =item B<unlink1>
2255#pod
2256#pod Similar to C<unlink0> except after file comparison using cmpstat, the
2257#pod filehandle is closed prior to attempting to unlink the file. This
2258#pod allows the file to be removed without using an END block, but does
2259#pod mean that the post-unlink comparison of the filehandle state provided
2260#pod by C<unlink0> is not available.
2261#pod
2262#pod unlink1($fh, $path)
2263#pod or die "Error closing and unlinking file";
2264#pod
2265#pod Usually called from the object destructor when using the OO interface.
2266#pod
2267#pod Not exported by default.
2268#pod
2269#pod This function is disabled if the global variable $KEEP_ALL is true.
2270#pod
2271#pod Can call croak() if there is a security anomaly during the stat()
2272#pod comparison.
2273#pod
2274#pod Current API available since 0.14.
2275#pod
2276#pod =cut
2277
2278
# spent 20.3s (2.18+18.1) within File::Temp::unlink1 which was called 133035 times, avg 153µs/call: # 133035 times (2.18s+18.1s) by File::Temp::DESTROY at line 1262, avg 153µs/call
sub unlink1 {
227913303567.2ms croak 'Usage: unlink1(filehandle, filename)'
2280 unless scalar(@_) == 2;
2281
2282 # Read args
228313303566.9ms my ($fh, $path) = @_;
2284
2285133035245ms1330358.02s cmpstat($fh, $path) or return 0;
# spent 8.02s making 133035 calls to File::Temp::cmpstat, avg 60µs/call
2286
2287 # Close the file
22881330351.66s1330351.22s close( $fh ) or return 0;
# spent 1.22s making 133035 calls to File::Temp::CORE:close, avg 9µs/call
2289
2290 # Make sure the file is writable (for windows)
2291133035132ms1330354.28s _force_writable( $path );
# spent 4.28s making 133035 calls to File::Temp::_force_writable, avg 32µs/call
2292
2293 # return early (without unlink) if we have been instructed to retain files.
229413303529.0ms return 1 if $KEEP_ALL;
2295
2296 # remove the file
22971330355.38s1330354.62s return unlink($path);
# spent 4.62s making 133035 calls to File::Temp::CORE:unlink, avg 35µs/call
2298}
2299
2300#pod =item B<cleanup>
2301#pod
2302#pod Calling this function will cause any temp files or temp directories
2303#pod that are registered for removal to be removed. This happens automatically
2304#pod when the process exits but can be triggered manually if the caller is sure
2305#pod that none of the temp files are required. This method can be registered as
2306#pod an Apache callback.
2307#pod
2308#pod Note that if a temp directory is your current directory, it cannot be
2309#pod removed. C<chdir()> out of the directory first before calling
2310#pod C<cleanup()>. (For the cleanup at program exit when the CLEANUP flag
2311#pod is set, this happens automatically.)
2312#pod
2313#pod On OSes where temp files are automatically removed when the temp file
2314#pod is closed, calling this function will have no effect other than to remove
2315#pod temporary directories (which may include temporary files).
2316#pod
2317#pod File::Temp::cleanup();
2318#pod
2319#pod Not exported by default.
2320#pod
2321#pod Current API available since 0.15.
2322#pod
2323#pod =back
2324#pod
2325#pod =head1 PACKAGE VARIABLES
2326#pod
2327#pod These functions control the global state of the package.
2328#pod
2329#pod =over 4
2330#pod
2331#pod =item B<safe_level>
2332#pod
2333#pod Controls the lengths to which the module will go to check the safety of the
2334#pod temporary file or directory before proceeding.
2335#pod Options are:
2336#pod
2337#pod =over 8
2338#pod
2339#pod =item STANDARD
2340#pod
2341#pod Do the basic security measures to ensure the directory exists and is
2342#pod writable, that temporary files are opened only if they do not already
2343#pod exist, and that possible race conditions are avoided. Finally the
2344#pod L<unlink0|"unlink0"> function is used to remove files safely.
2345#pod
2346#pod =item MEDIUM
2347#pod
2348#pod In addition to the STANDARD security, the output directory is checked
2349#pod to make sure that it is owned either by root or the user running the
2350#pod program. If the directory is writable by group or by other, it is then
2351#pod checked to make sure that the sticky bit is set.
2352#pod
2353#pod Will not work on platforms that do not support the C<-k> test
2354#pod for sticky bit.
2355#pod
2356#pod =item HIGH
2357#pod
2358#pod In addition to the MEDIUM security checks, also check for the
2359#pod possibility of ``chown() giveaway'' using the L<POSIX|POSIX>
2360#pod sysconf() function. If this is a possibility, each directory in the
2361#pod path is checked in turn for safeness, recursively walking back to the
2362#pod root directory.
2363#pod
2364#pod For platforms that do not support the L<POSIX|POSIX>
2365#pod C<_PC_CHOWN_RESTRICTED> symbol (for example, Windows NT) it is
2366#pod assumed that ``chown() giveaway'' is possible and the recursive test
2367#pod is performed.
2368#pod
2369#pod =back
2370#pod
2371#pod The level can be changed as follows:
2372#pod
2373#pod File::Temp->safe_level( File::Temp::HIGH );
2374#pod
2375#pod The level constants are not exported by the module.
2376#pod
2377#pod Currently, you must be running at least perl v5.6.0 in order to
2378#pod run with MEDIUM or HIGH security. This is simply because the
2379#pod safety tests use functions from L<Fcntl|Fcntl> that are not
2380#pod available in older versions of perl. The problem is that the version
2381#pod number for Fcntl is the same in perl 5.6.0 and in 5.005_03 even though
2382#pod they are different versions.
2383#pod
2384#pod On systems that do not support the HIGH or MEDIUM safety levels
2385#pod (for example Win NT or OS/2) any attempt to change the level will
2386#pod be ignored. The decision to ignore rather than raise an exception
2387#pod allows portable programs to be written with high security in mind
2388#pod for the systems that can support this without those programs failing
2389#pod on systems where the extra tests are irrelevant.
2390#pod
2391#pod If you really need to see whether the change has been accepted
2392#pod simply examine the return value of C<safe_level>.
2393#pod
2394#pod $newlevel = File::Temp->safe_level( File::Temp::HIGH );
2395#pod die "Could not change to high security"
2396#pod if $newlevel != File::Temp::HIGH;
2397#pod
2398#pod Available since 0.05.
2399#pod
2400#pod =cut
2401
2402{
2403 # protect from using the variable itself
24041200ns my $LEVEL = STANDARD;
2405
# spent 267ms within File::Temp::safe_level which was called 266070 times, avg 1µs/call: # 266070 times (267ms+0s) by File::Temp::_gettemp at line 470, avg 1µs/call
sub safe_level {
240626607052.9ms my $self = shift;
240726607048.7ms if (@_) {
2408 my $level = shift;
2409 if (($level != STANDARD) && ($level != MEDIUM) && ($level != HIGH)) {
2410 carp "safe_level: Specified level ($level) not STANDARD, MEDIUM or HIGH - ignoring\n" if $^W;
2411 } else {
2412 # Don't allow this on perl 5.005 or earlier
2413 if ($] < 5.006 && $level != STANDARD) {
2414 # Cant do MEDIUM or HIGH checks
2415 croak "Currently requires perl 5.006 or newer to do the safe checks";
2416 }
2417 # Check that we are allowed to change level
2418 # Silently ignore if we can not.
2419 $LEVEL = $level if _can_do_level($level);
2420 }
2421 }
2422266070553ms return $LEVEL;
2423 }
2424}
2425
2426#pod =item TopSystemUID
2427#pod
2428#pod This is the highest UID on the current system that refers to a root
2429#pod UID. This is used to make sure that the temporary directory is
2430#pod owned by a system UID (C<root>, C<bin>, C<sys> etc) rather than
2431#pod simply by root.
2432#pod
2433#pod This is required since on many unix systems C</tmp> is not owned
2434#pod by root.
2435#pod
2436#pod Default is to assume that any UID less than or equal to 10 is a root
2437#pod UID.
2438#pod
2439#pod File::Temp->top_system_uid(10);
2440#pod my $topid = File::Temp->top_system_uid;
2441#pod
2442#pod This value can be adjusted to reduce security checking if required.
2443#pod The value is only relevant when C<safe_level> is set to MEDIUM or higher.
2444#pod
2445#pod Available since 0.05.
2446#pod
2447#pod =cut
2448
2449{
24502200ns my $TopSystemUID = 10;
24511200ns $TopSystemUID = 197108 if $^O eq 'interix'; # "Administrator"
2452 sub top_system_uid {
2453 my $self = shift;
2454 if (@_) {
2455 my $newuid = shift;
2456 croak "top_system_uid: UIDs should be numeric"
2457 unless $newuid =~ /^\d+$/s;
2458 $TopSystemUID = $newuid;
2459 }
2460 return $TopSystemUID;
2461 }
2462}
2463
2464#pod =item B<$KEEP_ALL>
2465#pod
2466#pod Controls whether temporary files and directories should be retained
2467#pod regardless of any instructions in the program to remove them
2468#pod automatically. This is useful for debugging but should not be used in
2469#pod production code.
2470#pod
2471#pod $File::Temp::KEEP_ALL = 1;
2472#pod
2473#pod Default is for files to be removed as requested by the caller.
2474#pod
2475#pod In some cases, files will only be retained if this variable is true
2476#pod when the file is created. This means that you can not create a temporary
2477#pod file, set this variable and expect the temp file to still be around
2478#pod when the program exits.
2479#pod
2480#pod =item B<$DEBUG>
2481#pod
2482#pod Controls whether debugging messages should be enabled.
2483#pod
2484#pod $File::Temp::DEBUG = 1;
2485#pod
2486#pod Default is for debugging mode to be disabled.
2487#pod
2488#pod Available since 0.15.
2489#pod
2490#pod =back
2491#pod
2492#pod =head1 WARNING
2493#pod
2494#pod For maximum security, endeavour always to avoid ever looking at,
2495#pod touching, or even imputing the existence of the filename. You do not
2496#pod know that that filename is connected to the same file as the handle
2497#pod you have, and attempts to check this can only trigger more race
2498#pod conditions. It's far more secure to use the filehandle alone and
2499#pod dispense with the filename altogether.
2500#pod
2501#pod If you need to pass the handle to something that expects a filename
2502#pod then on a unix system you can use C<"/dev/fd/" . fileno($fh)> for
2503#pod arbitrary programs. Perl code that uses the 2-argument version of
2504#pod C<< open >> can be passed C<< "+<=&" . fileno($fh) >>. Otherwise you
2505#pod will need to pass the filename. You will have to clear the
2506#pod close-on-exec bit on that file descriptor before passing it to another
2507#pod process.
2508#pod
2509#pod use Fcntl qw/F_SETFD F_GETFD/;
2510#pod fcntl($tmpfh, F_SETFD, 0)
2511#pod or die "Can't clear close-on-exec flag on temp fh: $!\n";
2512#pod
2513#pod =head2 Temporary files and NFS
2514#pod
2515#pod Some problems are associated with using temporary files that reside
2516#pod on NFS file systems and it is recommended that a local filesystem
2517#pod is used whenever possible. Some of the security tests will most probably
2518#pod fail when the temp file is not local. Additionally, be aware that
2519#pod the performance of I/O operations over NFS will not be as good as for
2520#pod a local disk.
2521#pod
2522#pod =head2 Forking
2523#pod
2524#pod In some cases files created by File::Temp are removed from within an
2525#pod END block. Since END blocks are triggered when a child process exits
2526#pod (unless C<POSIX::_exit()> is used by the child) File::Temp takes care
2527#pod to only remove those temp files created by a particular process ID. This
2528#pod means that a child will not attempt to remove temp files created by the
2529#pod parent process.
2530#pod
2531#pod If you are forking many processes in parallel that are all creating
2532#pod temporary files, you may need to reset the random number seed using
2533#pod srand(EXPR) in each child else all the children will attempt to walk
2534#pod through the same set of random file names and may well cause
2535#pod themselves to give up if they exceed the number of retry attempts.
2536#pod
2537#pod =head2 Directory removal
2538#pod
2539#pod Note that if you have chdir'ed into the temporary directory and it is
2540#pod subsequently cleaned up (either in the END block or as part of object
2541#pod destruction), then you will get a warning from File::Path::rmtree().
2542#pod
2543#pod =head2 Taint mode
2544#pod
2545#pod If you need to run code under taint mode, updating to the latest
2546#pod L<File::Spec> is highly recommended. On Windows, if the directory
2547#pod given by L<File::Spec::tmpdir> isn't writable, File::Temp will attempt
2548#pod to fallback to the user's local application data directory or croak
2549#pod with an error.
2550#pod
2551#pod =head2 BINMODE
2552#pod
2553#pod The file returned by File::Temp will have been opened in binary mode
2554#pod if such a mode is available. If that is not correct, use the C<binmode()>
2555#pod function to change the mode of the filehandle.
2556#pod
2557#pod Note that you can modify the encoding of a file opened by File::Temp
2558#pod also by using C<binmode()>.
2559#pod
2560#pod =head1 HISTORY
2561#pod
2562#pod Originally began life in May 1999 as an XS interface to the system
2563#pod mkstemp() function. In March 2000, the OpenBSD mkstemp() code was
2564#pod translated to Perl for total control of the code's
2565#pod security checking, to ensure the presence of the function regardless of
2566#pod operating system and to help with portability. The module was shipped
2567#pod as a standard part of perl from v5.6.1.
2568#pod
2569#pod Thanks to Tom Christiansen for suggesting that this module
2570#pod should be written and providing ideas for code improvements and
2571#pod security enhancements.
2572#pod
2573#pod =head1 SEE ALSO
2574#pod
2575#pod L<POSIX/tmpnam>, L<POSIX/tmpfile>, L<File::Spec>, L<File::Path>
2576#pod
2577#pod See L<IO::File> and L<File::MkTemp>, L<Apache::TempFile> for
2578#pod different implementations of temporary file handling.
2579#pod
2580#pod See L<File::Tempdir> for an alternative object-oriented wrapper for
2581#pod the C<tempdir> function.
2582#pod
2583#pod =cut
2584
2585package ## hide from PAUSE
25861200ns File::Temp::Dir;
2587
25881300nsour $VERSION = '0.2311';
2589
2590218µs251µs
# spent 30µs (9+21) within File::Temp::Dir::BEGIN@2590 which was called: # once (9µs+21µs) by main::BEGIN@18 at line 2590
use File::Path qw/ rmtree /;
# spent 30µs making 1 call to File::Temp::Dir::BEGIN@2590 # spent 21µs making 1 call to Exporter::import
2591228µs28µs
# spent 6µs (4+2) within File::Temp::Dir::BEGIN@2591 which was called: # once (4µs+2µs) by main::BEGIN@18 at line 2591
use strict;
# spent 6µs making 1 call to File::Temp::Dir::BEGIN@2591 # spent 2µs making 1 call to strict::import
259213µs120µs
# spent 24µs (4+20) within File::Temp::Dir::BEGIN@2592 which was called: # once (4µs+20µs) by main::BEGIN@18 at line 2594
use overload '""' => "STRINGIFY",
# spent 20µs making 1 call to overload::import
2593 '0+' => \&File::Temp::NUMIFY,
25941178µs124µs fallback => 1;
# spent 24µs making 1 call to File::Temp::Dir::BEGIN@2592
2595
2596# private class specifically to support tempdir objects
2597# created by File::Temp->newdir
2598
2599# ostensibly the same method interface as File::Temp but without
2600# inheriting all the IO::Seekable methods and other cruft
2601
2602# Read-only - returns the name of the temp directory
2603
2604sub dirname {
2605 my $self = shift;
2606 return $self->{DIRNAME};
2607}
2608
2609sub STRINGIFY {
2610 my $self = shift;
2611 return $self->dirname;
2612}
2613
2614sub unlink_on_destroy {
2615 my $self = shift;
2616 if (@_) {
2617 $self->{CLEANUP} = shift;
2618 }
2619 return $self->{CLEANUP};
2620}
2621
2622sub DESTROY {
2623 my $self = shift;
2624 local($., $@, $!, $^E, $?);
2625 if ($self->unlink_on_destroy &&
2626 $$ == $self->{LAUNCHPID} && !$File::Temp::KEEP_ALL) {
2627 if (-d $self->{REALNAME}) {
2628 # Some versions of rmtree will abort if you attempt to remove
2629 # the directory you are sitting in. We protect that and turn it
2630 # into a warning. We do this because this occurs during object
2631 # destruction and so can not be caught by the user.
2632 eval { rmtree($self->{REALNAME}, $File::Temp::DEBUG, 0); };
2633 warn $@ if ($@ && $^W);
2634 }
2635 }
2636}
2637
2638118µs1;
2639
2640# vim: ts=2 sts=2 sw=2 et:
2641
2642__END__
 
# spent 8.43s within File::Temp::CORE:chmod which was called 399105 times, avg 21µs/call: # 266070 times (7.39s+0s) by File::Temp::_force_writable at line 645, avg 28µs/call # 133035 times (1.04s+0s) by File::Temp::_gettemp at line 521, avg 8µs/call
sub File::Temp::CORE:chmod; # opcode
# spent 1.22s within File::Temp::CORE:close which was called 133035 times, avg 9µs/call: # 133035 times (1.22s+0s) by File::Temp::unlink1 at line 2288, avg 9µs/call
sub File::Temp::CORE:close; # opcode
# spent 431ms within File::Temp::CORE:ftdir which was called 133035 times, avg 3µs/call: # 133035 times (431ms+0s) by File::Temp::_gettemp at line 461, avg 3µs/call
sub File::Temp::CORE:ftdir; # opcode
# spent 486ms within File::Temp::CORE:ftfile which was called 133035 times, avg 4µs/call: # 133035 times (486ms+0s) by File::Temp::cmpstat at line 2217, avg 4µs/call
sub File::Temp::CORE:ftfile; # opcode
# spent 450ms within File::Temp::CORE:ftis which was called 133035 times, avg 3µs/call: # 133035 times (450ms+0s) by File::Temp::_gettemp at line 457, avg 3µs/call
sub File::Temp::CORE:ftis; # opcode
# spent 243ms within File::Temp::CORE:regcomp which was called 133035 times, avg 2µs/call: # 133035 times (243ms+0s) by File::Temp::_replace_XX at line 635, avg 2µs/call
sub File::Temp::CORE:regcomp; # opcode
# spent 1µs within File::Temp::CORE:sort which was called: # once (1µs+0s) by File::Temp::cleanup at line 880
sub File::Temp::CORE:sort; # opcode
# spent 1.08s within File::Temp::CORE:stat which was called 266070 times, avg 4µs/call: # 133035 times (700ms+0s) by File::Temp::cmpstat at line 2200, avg 5µs/call # 133035 times (381ms+0s) by File::Temp::cmpstat at line 2209, avg 3µs/call
sub File::Temp::CORE:stat; # opcode
# spent 1.06s within File::Temp::CORE:subst which was called 133035 times, avg 8µs/call: # 133035 times (1.06s+0s) by File::Temp::_replace_XX at line 635, avg 8µs/call
sub File::Temp::CORE:subst; # opcode
# spent 1.17s within File::Temp::CORE:substcont which was called 1463385 times, avg 797ns/call: # 1463385 times (1.17s+0s) by File::Temp::_replace_XX at line 635, avg 797ns/call
sub File::Temp::CORE:substcont; # opcode
# spent 6.49s within File::Temp::CORE:sysopen which was called 133035 times, avg 49µs/call: # 133035 times (6.49s+0s) by File::Temp::_gettemp at line 516, avg 49µs/call
sub File::Temp::CORE:sysopen; # opcode
# spent 4.62s within File::Temp::CORE:unlink which was called 133035 times, avg 35µs/call: # 133035 times (4.62s+0s) by File::Temp::unlink1 at line 2297, avg 35µs/call
sub File::Temp::CORE:unlink; # opcode
# spent 200ns within File::Temp::__ANON__ which was called: # once (200ns+0s) by File::Temp::BEGIN@147 at line 147
sub File::Temp::__ANON__; # xsub