summaryrefslogtreecommitdiff
path: root/Master/tlpkg/tlperl/lib/Win32
diff options
context:
space:
mode:
authorKarl Berry <karl@freefriends.org>2014-04-23 21:46:20 +0000
committerKarl Berry <karl@freefriends.org>2014-04-23 21:46:20 +0000
commit300c1eb6d37d46078d448d6d58938d5a80cd68ff (patch)
tree23a0a8b9f8f5460b405119c4d3c163d2d488ca5e /Master/tlpkg/tlperl/lib/Win32
parented55d86b7c5e18f6eccce80a1fb1423ca40a23b5 (diff)
(tl)perl 5.18.2 for windows from siep
git-svn-id: svn://tug.org/texlive/trunk@33648 c570f23f-e606-0410-a88d-b1316a301751
Diffstat (limited to 'Master/tlpkg/tlperl/lib/Win32')
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/API.pm1075
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/API/Callback.pm502
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/API/Struct.pm245
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/API/Test.pm26
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/API/Type.pm183
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/OLE.pm26
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/OLE/Const.pm6
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/OLE/NLS.pm2
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/OLE/Variant.pm12
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/Process/Info.pm52
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/Process/Info/NT.pm30
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/Process/Info/PT.pm33
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/Process/Info/WMI.pm12
-rw-r--r--Master/tlpkg/tlperl/lib/Win32/Shortcut.pm10
14 files changed, 1831 insertions, 383 deletions
diff --git a/Master/tlpkg/tlperl/lib/Win32/API.pm b/Master/tlpkg/tlperl/lib/Win32/API.pm
index 8a08b01033a..6accc691db8 100644
--- a/Master/tlpkg/tlperl/lib/Win32/API.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/API.pm
@@ -14,13 +14,41 @@
#######################################################################
package Win32::API;
+ use strict;
+ use warnings;
+ use Config;
+BEGIN {
+ require Exporter; # to export the constants to the main:: space
+ require DynaLoader; # to dynuhlode the module.
-require Exporter; # to export the constants to the main:: space
-require DynaLoader; # to dynuhlode the module.
-@ISA = qw( Exporter DynaLoader );
+ sub ISCYG ();
+ eval "sub ISCYG () { ".($^O eq 'cygwin' ? 1 : 0)."}";
+ no warnings 'uninitialized';
+ die "Win32::API on Cygwin requires the cygpath tool on PATH"
+ if ISCYG && index(`cygpath --help`,'Usage: cygpath') == -1;
-use vars qw( $DEBUG );
-$DEBUG = 0;
+ use vars qw( $DEBUG $sentinal @ISA @EXPORT_OK $VERSION );
+
+ @ISA = qw( Exporter DynaLoader );
+ @EXPORT_OK = qw( ReadMemory IsBadReadPtr MoveMemory
+ WriteMemory SafeReadWideCString ); # symbols to export on request
+
+ use Scalar::Util qw( looks_like_number weaken);
+
+ $DEBUG = 0;
+
+ sub ERROR_NOACCESS () { 998 }
+ sub ERROR_NOT_ENOUGH_MEMORY () { 8 }
+ sub ERROR_INVALID_PARAMETER () { 87 }
+ sub APICONTROL_CC_STD () { 0 }
+ sub APICONTROL_CC_C () { 1 }
+ sub APICONTROL_CC_mask () { 0x7 }
+ sub APICONTROL_UseMI64 () { 0x8 }
+ sub APICONTROL_is_more () { 0x10 }
+ sub APICONTROL_has_proto() { 0x20 }
+ eval " *Win32::API::Type::PTRSIZE = *Win32::API::More::PTRSIZE = *PTRSIZE = sub () { ".$Config{ptrsize}." }";
+ eval " *Win32::API::Type::IVSIZE = *Win32::API::More::IVSIZE = *IVSIZE = sub () { ".$Config{ivsize}." }";
+}
sub DEBUG {
if ($Win32::API::DEBUG) {
@@ -38,8 +66,6 @@ use File::Basename ();
#######################################################################
# STATIC OBJECT PROPERTIES
#
-$VERSION = '0.68';
-
#### some package-global hash to
#### keep track of the imported
#### libraries and procedures
@@ -49,125 +75,211 @@ my %Procedures = ();
#######################################################################
# dynamically load in the API extension module.
-#
-bootstrap Win32::API;
+# BEGIN required for constant subs in BOOT:
+BEGIN {
+ $VERSION = '0.77';
+ bootstrap Win32::API;
+}
#######################################################################
# PUBLIC METHODS
#
sub new {
- my ($class, $dll, $proc, $in, $out, $callconvention) = @_;
- my $hdll;
- my $self = {};
-
- if ($^O eq 'cygwin' and $dll ne File::Basename::basename($dll)) {
-
- # need to convert $dll to win32 path
- # isn't there an API for this?
- my $newdll = `cygpath -w "$dll"`;
- chomp $newdll;
- DEBUG "(PM)new: converted '$dll' to\n '$newdll'\n";
- $dll = $newdll;
- }
-
- #### avoid loading a library more than once
- if (exists($Libraries{$dll})) {
- DEBUG "Win32::API::new: Library '$dll' already loaded, handle=$Libraries{$dll}\n";
- $hdll = $Libraries{$dll};
+ die "Win32::API/More::new/Import is a class method that takes 2 to 6 parameters, see POD"
+ if @_ < 3 || @_ > 7;
+ my ($class, $dll, $hproc, $ccnum, $outnum) = (shift, shift);
+ if(! defined $dll){
+ $hproc = shift;
}
- else {
- DEBUG "Win32::API::new: Loading library '$dll'\n";
- $hdll = Win32::API::LoadLibrary($dll);
-
-# $Libraries{$dll} = $hdll;
+ my ($proc, $in, $out, $callconvention) = @_;
+ my ($hdll, $freedll, $proto, $stackunwind) = (0, 0, 0, 0);
+ my $self = {};
+ if(! defined $hproc){
+ if (ISCYG() and $dll ne File::Basename::basename($dll)) {
+
+ # need to convert $dll to win32 path
+ # isn't there an API for this?
+ my $newdll = `cygpath -w "$dll"`;
+ chomp $newdll;
+ DEBUG "(PM)new: converted '$dll' to\n '$newdll'\n";
+ $dll = $newdll;
+ }
+
+ #### avoid loading a library more than once
+ if (exists($Libraries{$dll})) {
+ DEBUG "Win32::API::new: Library '$dll' already loaded, handle=$Libraries{$dll}\n";
+ $hdll = $Libraries{$dll};
+ }
+ else {
+ DEBUG "Win32::API::new: Loading library '$dll'\n";
+ $hdll = Win32::API::LoadLibrary($dll);
+ $freedll = 1;
+ # $Libraries{$dll} = $hdll;
+ }
+
+ #### if the dll can't be loaded, set $! to Win32's GetLastError()
+ if (!$hdll) {
+ $! = Win32::GetLastError();
+ DEBUG "FAILED Loading library '$dll': $^E\n";
+ return undef;
+ }
}
-
- #### if the dll can't be loaded, set $! to Win32's GetLastError()
- if (!$hdll) {
- $! = Win32::GetLastError();
- DEBUG "FAILED Loading library '$dll': $!\n";
- delete $Libraries{$dll};
- return undef;
+ else{
+ if(!looks_like_number($hproc) || IsBadReadPtr($hproc, 4)){
+ Win32::SetLastError(ERROR_NOACCESS);
+ DEBUG "FAILED Function pointer '$hproc' is not a valid memory location\n";
+ return undef;
+ }
}
-
- #### determine if we have a prototype or not
+ #### determine if we have a prototype or not, outtype is for future use in XS
if ((not defined $in) and (not defined $out)) {
- ($proc, $self->{in}, $self->{intypes}, $self->{out}, $self->{cdecl}) =
- parse_prototype($proc);
- return undef unless $proc;
- $self->{proto} = 1;
+ ($proc, $self->{in}, $self->{intypes}, $outnum, $self->{outtype},
+ $ccnum) = parse_prototype($class, $proc);
+ if( ! $proc ){
+ Win32::API::FreeLibrary($hdll) if $freedll;
+ Win32::SetLastError(ERROR_INVALID_PARAMETER);
+ return undef;
+ }
+ $proto = 1;
}
else {
$self->{in} = [];
+ my $self_in = $self->{in}; #avoid hash derefing
if (ref($in) eq 'ARRAY') {
foreach (@$in) {
- push(@{$self->{in}}, type_to_num($_));
+ push(@{$self_in}, $class->type_to_num($_));
}
}
else {
my @in = split '', $in;
foreach (@in) {
- push(@{$self->{in}}, type_to_num($_));
+ push(@{$self_in}, $class->type_to_num($_));
+ }
+ }#'V' must be one and ONLY letter for "in"
+ foreach(@{$self_in}){
+ if($_ == 0){
+ if(@{$self_in} != 1){
+ Win32::API::FreeLibrary($hdll) if $freedll;
+ die "Win32::API 'V' for in prototype must be the only parameter";
+ } else {undef(@{$self_in});} #empty arr, as if in param was ""
}
}
- $self->{out} = type_to_num($out);
- $self->{cdecl} = calltype_to_num($callconvention);
+ $outnum = $class->type_to_num($out, 1);
+ $ccnum = calltype_to_num($callconvention);
}
- #### first try to import the function of given name...
- my $hproc = Win32::API::GetProcAddress($hdll, $proc);
-
- #### ...then try appending either A or W (for ASCII or Unicode)
- if (!$hproc) {
- my $tproc = $proc;
- $tproc .= (IsUnicode() ? "W" : "A");
-
- # print "Win32::API::new: procedure not found, trying '$tproc'...\n";
- $hproc = Win32::API::GetProcAddress($hdll, $tproc);
+ if(!$hproc){ #if not non DLL func
+ #### first try to import the function of given name...
+ $hproc = Win32::API::GetProcAddress($hdll, $proc);
+
+ #### ...then try appending either A or W (for ASCII or Unicode)
+ if (!$hproc) {
+ my $tproc = $proc;
+ $tproc .= (IsUnicode() ? "W" : "A");
+
+ # print "Win32::API::new: procedure not found, trying '$tproc'...\n";
+ $hproc = Win32::API::GetProcAddress($hdll, $tproc);
+ }
+
+ #### ...if all that fails, give up, $! setting is back compat, $! is deprecated
+ if (!$hproc) {
+ my $err = $! = Win32::GetLastError();
+ DEBUG "FAILED GetProcAddress for Proc '$proc': $^E\n";
+ Win32::API::FreeLibrary($hdll) if $freedll;
+ Win32::SetLastError($err);
+ return undef;
+ }
+ DEBUG "GetProcAddress('$proc') = '$hproc'\n";
}
-
- #### ...if all that fails, set $! accordingly
- if (!$hproc) {
- $! = Win32::GetLastError();
- DEBUG "FAILED GetProcAddress for Proc '$proc': $!\n";
+ else {
+ DEBUG "Using non-DLL function pointer '$hproc' for '$proc'\n";
+ }
+ if(PTRSIZE == 4 && $ccnum == APICONTROL_CC_C) {#fold out on WIN64
+ #calculate add to ESP amount, in units of 4, will be *4ed later
+ $stackunwind += $_ == T_QUAD || $_ == T_DOUBLE ? 2 : 1 for(@{$self->{in}});
+ if($stackunwind > 0xFFFF) {
+ goto too_many_in_params;
+ }
+ }
+ # if a prototype has 8 byte types on 32bit, $stackunwind will be higher than
+ # length of {in} letter array, so 2 different checks need to be done
+ if($#{$self->{in}} > 0xFFFF) {
+ too_many_in_params:
+ DEBUG "FAILED This function has too many parameters (> ~65535) \n";
+ Win32::API::FreeLibrary($hdll) if $freedll;
+ Win32::SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return undef;
}
- DEBUG "GetProcAddress('$proc') = '$hproc'\n";
-
#### ok, let's stuff the object
$self->{procname} = $proc;
$self->{dll} = $hdll;
$self->{dllname} = $dll;
- $self->{proc} = $hproc;
- #### keep track of the imported function
- $Libraries{$dll} = $hdll;
- $Procedures{$dll}++;
+ $outnum &= ~T_FLAG_NUMERIC;
+ my $control;
+ $self->{weakapi} = \$control;
+ weaken($self->{weakapi});
+ $control = pack( 'L'
+ .'L'
+ .(PTRSIZE == 8 ? 'Q' : 'L')
+ .(PTRSIZE == 8 ? 'Q' : 'L')
+ .(PTRSIZE == 8 ? 'Q' : 'L')
+ .(PTRSIZE == 8 ? '' : 'L')
+ ,($class eq "Win32::API::More" ? APICONTROL_is_more : 0)
+ | ($proto ? APICONTROL_has_proto : 0)
+ | $ccnum
+ | (PTRSIZE == 8 ? 0 : $stackunwind << 8)
+ | $outnum << 24
+ , scalar(@{$self->{in}}) * PTRSIZE #in param count, in SV * units
+ , $hproc
+ , \($self->{weakapi})+0 #weak api obj ref
+ , (exists $self->{intypes} ? ($self->{intypes})+0 : 0)
+ , 0); #padding to align to 8 bytes on 32 bit only
+ #align to 16 bytes
+ $control .= "\x00" x ((((length($control)+ 15) >> 4) << 4)-length($control));
+ #make a APIPARAM template array
+ my ($i, $arr_end) = (0, scalar(@{$self->{in}}));
+ for(; $i< $arr_end; $i++) {
+ my $tin = $self->{in}[$i];
+ #unsigned meaningless no sign vs zero extends are done bc uv/iv is
+ #the biggest native integer on the cpu, big to small is truncation
+ #numeric is implemented as T_NUMCHAR for in, keeps asm jumptable clean
+ $tin &= ~(T_FLAG_UNSIGNED|T_FLAG_NUMERIC);
+ $tin--; #T_VOID doesn't exist as in param in XS
+ #put index of param array slice in unused space for croaks, why not?
+ $control .= "\x00" x 8 . pack('CCSSS', $tin, 0, 0, $i, $i+1);
+ }
+ _Align($control, 16); #align the whole PVX to 16 bytes for SSE moves
+ #### keep track of the imported function
+ if(defined $dll){
+ $Libraries{$dll} = $hdll;
+ $Procedures{$dll}++;
+ }
DEBUG "Object blessed!\n";
- #### cast the spell
- bless($self, $class);
- return $self;
+ my $ref = bless(\$control, $class);
+ SetMagicSV($ref, $self);
+ return $ref;
}
sub Import {
- my ($class, $dll, $proc, $in, $out, $callconvention) = @_;
- $Imported{"$dll:$proc"} = Win32::API->new($dll, $proc, $in, $out, $callconvention)
- or return 0;
- my $P = (caller)[0];
- eval qq(
- sub ${P}::$Imported{"$dll:$proc"}->{procname} { \$Win32::API::Imported{"$dll:$proc"}->Call(\@_); }
- );
- return $@ ? 0 : 1;
+ my $closure = shift->new(@_)
+ or return undef;
+ my $procname = ${Win32::API::GetMagicSV($closure)}{procname};
+ #dont allow "sub main:: {0;}"
+ Win32::SetLastError(ERROR_INVALID_PARAMETER), return undef if $procname eq '';
+ _ImportXS($closure, (caller)[0].'::'.$procname);
+ return $closure;
}
#######################################################################
# PRIVATE METHODS
#
sub DESTROY {
- my ($self) = @_;
+ my ($self) = GetMagicSV($_[0]);
+ return if ! defined $self->{dllname};
#### decrease this library's procedures reference count
$Procedures{$self->{dllname}}--;
@@ -180,131 +292,277 @@ sub DESTROY {
}
# Convert calling convention string (_cdecl|__stdcall)
-# to an integer (1|0). Unknown counts as __stdcall
+# to a C const. Unknown counts as __stdcall
#
sub calltype_to_num {
my $type = shift;
- if (!$type || $type eq "__stdcall") {
- return 0;
+ if (!$type || $type eq "__stdcall" || $type eq "WINAPI" || $type eq "NTAPI"
+ || $type eq "CALLBACK" ) {
+ return APICONTROL_CC_STD;
}
- elsif ($type eq "_cdecl") {
- return 1;
+ elsif ($type eq "_cdecl" || $type eq "__cdecl" || $type eq "WINAPIV") {
+ return APICONTROL_CC_C;
}
else {
warn "unknown calling convention: '$type'";
- return 0;
+ return APICONTROL_CC_STD;
}
}
+
sub type_to_num {
+ die "wrong class" if shift ne "Win32::API";
my $type = shift;
my $out = shift;
- my $num;
+ my ($num, $numeric);
+ if(index($type, 'num', 0) == 0){
+ substr($type, 0, length('num'), '');
+ $numeric = 1;
+ }
+ else{
+ $numeric = 0;
+ }
if ( $type eq 'N'
or $type eq 'n'
or $type eq 'l'
- or $type eq 'L')
+ or $type eq 'L'
+ or ( PTRSIZE == 8 and $type eq 'Q' || $type eq 'q'))
{
- $num = 1;
+ $num = T_NUMBER;
}
elsif ($type eq 'P'
or $type eq 'p')
{
- $num = 2;
+ $num = T_POINTER;
}
elsif ($type eq 'I'
or $type eq 'i')
{
- $num = 3;
+ $num = T_INTEGER;
}
elsif ($type eq 'f'
or $type eq 'F')
{
- $num = 4;
+ $num = T_FLOAT;
}
elsif ($type eq 'D'
or $type eq 'd')
{
- $num = 5;
+ $num = T_DOUBLE;
}
elsif ($type eq 'c'
or $type eq 'C')
{
- $num = 6;
+ $num = $numeric ? T_NUMCHAR : T_CHAR;
+ }
+ elsif (PTRSIZE == 4 and $type eq 'q' || $type eq 'Q')
+ {
+ $num = T_QUAD;
+ }
+ elsif($type eq '>'){
+ die "Win32::API does not support pass by copy structs as function arguments";
}
else {
- $num = 0;
+ $num = T_VOID; #'V' takes this branch, which is T_VOID in C
+ }#not valid return types of the C func
+ if(defined $out) {#b/B remains private/undocumented
+ die "Win32::API invalid return type, structs and ".
+ "callbacks as return types not supported"
+ if($type =~ m/^s|S|t|T|b|B|k|K$/);
}
- unless (defined $out) {
- if ( $type eq 's'
- or $type eq 'S')
+ else {#in type
+ if ($type eq 's' or $type eq 'S' or $type eq 't' or $type eq 'T')
{
- $num = 51;
+ $num = T_STRUCTURE;
}
elsif ($type eq 'b'
or $type eq 'B')
{
- $num = 22;
+ $num = T_POINTERPOINTER;
}
elsif ($type eq 'k'
or $type eq 'K')
{
- $num = 101;
+ $num = T_CODE;
}
}
+ $num |= T_FLAG_NUMERIC if $numeric;
return $num;
}
+package Win32::API::More;
+
+use vars qw( @ISA );
+@ISA = qw ( Win32::API );
+sub type_to_num {
+ die "wrong class" if shift ne "Win32::API::More";
+ my $type = shift;
+ my $out = shift;
+ my ($num, $numeric);
+ if(index($type, 'num', 0) == 0){
+ substr($type, 0, length('num'), '');
+ $numeric = 1;
+ }
+ else{
+ $numeric = 0;
+ }
+
+ if ( $type eq 'N'
+ or $type eq 'n'
+ or $type eq 'l'
+ or $type eq 'L'
+ or ( PTRSIZE == 8 and $type eq 'Q' || $type eq 'q')
+ or (! $out and # in XS short 'in's are interger/numbers code
+ $type eq 'S'
+ || $type eq 's'))
+ {
+ $num = Win32::API::T_NUMBER;
+ if(defined $out && ($type eq 'N' || $type eq 'L'
+ || $type eq 'S' || $type eq 'Q')){
+ $num |= Win32::API::T_FLAG_UNSIGNED;
+ }
+ }
+ elsif ($type eq 'P'
+ or $type eq 'p')
+ {
+ $num = Win32::API::T_POINTER;
+ }
+ elsif ($type eq 'I'
+ or $type eq 'i')
+ {
+ $num = Win32::API::T_INTEGER;
+ if(defined $out && $type eq 'I'){
+ $num |= Win32::API::T_FLAG_UNSIGNED;
+ }
+ }
+ elsif ($type eq 'f'
+ or $type eq 'F')
+ {
+ $num = Win32::API::T_FLOAT;
+ }
+ elsif ($type eq 'D'
+ or $type eq 'd')
+ {
+ $num = Win32::API::T_DOUBLE;
+ }
+ elsif ($type eq 'c'
+ or $type eq 'C')
+ {
+ $num = $numeric ? Win32::API::T_NUMCHAR : Win32::API::T_CHAR;
+ if(defined $out && $type eq 'C'){
+ $num |= Win32::API::T_FLAG_UNSIGNED;
+ }
+ }
+ elsif (PTRSIZE == 4 and $type eq 'q' || $type eq 'Q')
+ {
+ $num = Win32::API::T_QUAD;
+ if(defined $out && $type eq 'Q'){
+ $num |= Win32::API::T_FLAG_UNSIGNED;
+ }
+ }
+ elsif ($type eq 's') #4 is only used for out params
+ {
+ $num = Win32::API::T_SHORT;
+ }
+ elsif ($type eq 'S')
+ {
+ $num = Win32::API::T_SHORT | Win32::API::T_FLAG_UNSIGNED;
+ }
+ elsif($type eq '>'){
+ die "Win32::API does not support pass by copy structs as function arguments";
+ }
+ else {
+ $num = Win32::API::T_VOID; #'V' takes this branch, which is T_VOID in C
+ } #not valid return types of the C func
+ if(defined $out) {#b/B remains private/undocumented
+ die "Win32::API invalid return type, structs and ".
+ "callbacks as return types not supported"
+ if($type =~ m/^t|T|b|B|k|K$/);
+ }
+ else {#in type
+ if ( $type eq 't'
+ or $type eq 'T')
+ {
+ $num = Win32::API::T_STRUCTURE;
+ }
+ elsif ($type eq 'b'
+ or $type eq 'B')
+ {
+ $num = Win32::API::T_POINTERPOINTER;
+ }
+ elsif ($type eq 'k'
+ or $type eq 'K')
+ {
+ $num = Win32::API::T_CODE;
+ }
+ }
+ $num |= Win32::API::T_FLAG_NUMERIC if $numeric;
+ return $num;
+}
+package Win32::API;
+
sub parse_prototype {
- my ($proto) = @_;
+ my ($class, $proto) = @_;
my @in_params = ();
- my @in_types = ();
- if ($proto =~ /^\s*(\S+)(?:\s+(\w+))?\s+(\S+)\s*\(([^\)]*)\)/) {
- my $ret = $1;
- my $callconvention = $2;
- my $proc = $3;
- my $params = $4;
+ my @in_types = (); #one day create a BNF-ish formal grammer parser here
+ if ($proto =~ /^\s*((?:(?:un|)signed\s+|) #optional signedness
+ \S+)(?:\s*(\*)\s*|\s+) #type and maybe a *
+ (?:(\w+)\s+)? # maybe a calling convention
+ (\S+)\s* #func name
+ \(([^\)]*)\) #param list
+ /x) {
+ my $ret = $1.(defined($2)?$2:'');
+ my $callconvention = $3;
+ my $proc = $4;
+ my $params = $5;
$params =~ s/^\s+//;
$params =~ s/\s+$//;
DEBUG "(PM)parse_prototype: got PROC '%s'\n", $proc;
DEBUG "(PM)parse_prototype: got PARAMS '%s'\n", $params;
-
+
foreach my $param (split(/\s*,\s*/, $params)) {
my ($type, $name);
- if ($param =~ /(\S+)\s+(\S+)/) {
- ($type, $name) = ($1, $2);
+ #match "in_t* _var" "in_t * _var" "in_t *_var" "in_t _var" "in_t*_var" supported
+ #unsigned or signed or nothing as prefix supported
+ # "in_t ** _var" and "const in_t* var" not supported
+ if ($param =~ /((?:(?:un|)signed\s+|)\w+)(?:\s*(\*)\s*|\s+)(\w+)/) {
+ ($type, $name) = ($1.(defined($2)? $2:''), $3);
}
-
- if (Win32::API::Type::is_known($type)) {
+ {
+ no warnings 'uninitialized';
+ if($type eq '') {goto BADPROTO;} #something very wrong, bail out
+ }
+ my $packing = Win32::API::Type::packing($type);
+ if (defined $packing && $packing ne '>') {
if (Win32::API::Type::is_pointer($type)) {
DEBUG "(PM)parse_prototype: IN='%s' PACKING='%s' API_TYPE=%d\n",
$type,
- Win32::API::Type->packing($type),
- type_to_num('P');
- push(@in_params, type_to_num('P'));
+ $packing,
+ $class->type_to_num('P');
+ push(@in_params, $class->type_to_num('P'));
}
else {
DEBUG "(PM)parse_prototype: IN='%s' PACKING='%s' API_TYPE=%d\n",
$type,
- Win32::API::Type->packing($type),
- type_to_num(Win32::API::Type->packing($type));
- push(@in_params, type_to_num(Win32::API::Type->packing($type)));
+ $packing,
+ $class->type_to_num(Win32::API::Type->packing($type, undef, 1));
+ push(@in_params, $class->type_to_num(Win32::API::Type->packing($type, undef, 1)));
}
}
elsif (Win32::API::Struct::is_known($type)) {
DEBUG "(PM)parse_prototype: IN='%s' PACKING='%s' API_TYPE=%d\n",
- $type, 'S', type_to_num('S');
- push(@in_params, type_to_num('S'));
+ $type, 'T', Win32::API::More->type_to_num('T');
+ push(@in_params, Win32::API::More->type_to_num('T'));
}
else {
warn
"Win32::API::parse_prototype: WARNING unknown parameter type '$type'";
- push(@in_params, type_to_num('I'));
+ push(@in_params, $class->type_to_num('I'));
}
push(@in_types, $type);
@@ -317,36 +575,59 @@ sub parse_prototype {
DEBUG "parse_prototype: OUT='%s' PACKING='%s' API_TYPE=%d\n",
$ret,
Win32::API::Type->packing($ret),
- type_to_num('P');
- return ($proc, \@in_params, \@in_types, type_to_num('P'),
- calltype_to_num($callconvention));
+ $class->type_to_num('P');
+ return ($proc, \@in_params, \@in_types, $class->type_to_num('P', 1),
+ $ret, calltype_to_num($callconvention));
}
else {
DEBUG "parse_prototype: OUT='%s' PACKING='%s' API_TYPE=%d\n",
$ret,
Win32::API::Type->packing($ret),
- type_to_num(Win32::API::Type->packing($ret));
+ $class->type_to_num(Win32::API::Type->packing($ret, undef, 1), 1);
return (
$proc, \@in_params, \@in_types,
- type_to_num(Win32::API::Type->packing($ret)),
- calltype_to_num($callconvention)
+ $class->type_to_num(Win32::API::Type->packing($ret, undef, 1), 1),
+ $ret, calltype_to_num($callconvention)
);
}
}
else {
warn
"Win32::API::parse_prototype: WARNING unknown output parameter type '$ret'";
- return ($proc, \@in_params, \@in_types, type_to_num('I'),
- calltype_to_num($callconvention));
+ return ($proc, \@in_params, \@in_types, $class->type_to_num('I', 1),
+ $ret, calltype_to_num($callconvention));
}
}
else {
+ BADPROTO:
warn "Win32::API::parse_prototype: bad prototype '$proto'";
return undef;
}
}
+#
+# XXX hack, see the proper implementation in TODO
+# The point here is don't let fork children free the parent's DLLs.
+# CLONE runs on ::API and ::More, that's bad and causes a DLL leak, make sure
+# CLONE dups the DLL handles only once per CLONE
+# GetModuleHandleEx was not used since that is a WinXP and newer function, not Win2K.
+# GetModuleFileName was used to get full DLL pathname incase SxS/multiple DLLs
+# with same file name exist in the process. Even if the dll was loaded as a
+# relative path initially, later SxS can load a DLL with a different full path
+# yet same file name, and then LoadLibrary'ing the original relative path
+# might increase the refcount on the wrong DLL or return a different HMODULE
+sub CLONE {
+ return if $_[0] ne "Win32::API";
+
+ _my_cxt_clone();
+ foreach( keys %Libraries){
+ if($Libraries{$_} != Win32::API::LoadLibrary(Win32::API::GetModuleFileName($Libraries{$_}))){
+ die "Win32::API::CLONE unable to clone DLL \"$Libraries{$_}\" Unicode Problem??";
+ }
+ }
+}
+
1;
__END__
@@ -364,25 +645,50 @@ Win32::API - Perl Win32 API Import Facility
#### Method 1: with prototype
use Win32::API;
- $function = Win32::API->new(
- 'mydll, 'int sum_integers(int a, int b)',
+ $function = Win32::API::More->new(
+ 'mydll', 'int sum_integers(int a, int b)'
+ );
+ #### $^E is non-Cygwin only
+ die "Error: $^E" if ! $function;
+ #### or on Cygwin and non-Cygwin
+ die "Error: ".(Win32::FormatMessage(Win32::GetLastError())) if ! $function;
+ ####
+ $return = $function->Call(3, 2);
+
+ #### Method 2: with prototype and your function pointer
+
+ use Win32::API;
+ $function = Win32::API::More->new(
+ undef, 38123456, 'int name_ignored(int a, int b)'
);
+ die "Error: $^E" if ! $function; #$^E is non-Cygwin only
$return = $function->Call(3, 2);
+
+ #### Method 3: with parameter list
- #### Method 2: with parameter list
+ use Win32::API;
+ $function = Win32::API::More->new(
+ 'mydll', 'sum_integers', 'II', 'I'
+ );
+ die "Error: $^E" if ! $function; #$^E is non-Cygwin only
+ $return = $function->Call(3, 2);
+
+ #### Method 4: with parameter list and your function pointer
use Win32::API;
- $function = Win32::API->new(
- 'mydll', 'sum_integers', 'II', 'I',
+ $function = Win32::API::More->new(
+ undef, 38123456, 'name_ignored', 'II', 'I'
);
+ die "Error: $^E" if ! $function; #$^E is non-Cygwin only
$return = $function->Call(3, 2);
- #### Method 3: with Import
+ #### Method 5: with Import (slightly faster than ->Call)
use Win32::API;
- Win32::API->Import(
- 'mydll', 'int sum_integers(int a, int b)',
- );
+ $function = Win32::API::More->Import(
+ 'mydll', 'int sum_integers(int a, int b)'
+ );
+ die "Error: $^E" if ! $function; #$^E is non-Cygwin only
$return = sum_integers(3, 2);
@@ -395,7 +701,8 @@ Win32::API - Perl Win32 API Import Facility
=head1 ABSTRACT
With this module you can import and call arbitrary functions
-from Win32's Dynamic Link Libraries (DLL), without having
+from Win32's Dynamic Link Libraries (DLL) or arbitrary functions for
+which you have a pointer (MS COM, etc), without having
to write an XS extension. Note, however, that this module
can't do everything. In fact, parameters input and output is
limited to simpler cases.
@@ -411,9 +718,13 @@ A short example of how you can use this module (it just gets the PID of
the current process, eg. same as Perl's internal C<$$>):
use Win32::API;
- Win32::API->Import("kernel32", "int GetCurrentProcessId()");
+ Win32::API::More->Import("kernel32", "int GetCurrentProcessId()");
$PID = GetCurrentProcessId();
+Starting with 0.69. Win32::API initiated objects are deprecated due to numerous
+bugs and improvements, use Win32::API::More now. The use statement remains
+as C<use Win32::API;>.
+
The possibilities are nearly infinite (but not all are good :-).
Enjoy it.
@@ -424,33 +735,44 @@ To use this module put the following line at the beginning of your script:
use Win32::API;
You can now use the C<new()> function of the Win32::API module to create a
-new Win32::API object (see L<IMPORTING A FUNCTION>) and then invoke the
+new Win32::API::More object (see L<IMPORTING A FUNCTION>) and then invoke the
C<Call()> method on this object to perform a call to the imported API
(see L<CALLING AN IMPORTED FUNCTION>).
-Starting from version 0.40, you can also avoid creating a Win32::API object
+Starting from version 0.40, you can also avoid creating a Win32::API::More object
and instead automatically define a Perl sub with the same name of the API
-function you're importing. The details of the API definitions are the same,
-just the call is different:
+function you're importing. This 2nd way using C<Import> to create a sub instead
+of an object is slightly faster than doing C<-E<gt>Call()>. The details of the
+API definitions are the same, just the method name is different:
- my $GetCurrentProcessId = Win32::API->new(
+ my $GetCurrentProcessId = Win32::API::More->new(
"kernel32", "int GetCurrentProcessId()"
);
+ die "Failed to import GetCurrentProcessId" if !$GetCurrentProcessId;
+ $GetCurrentProcessId->UseMI64(1);
my $PID = $GetCurrentProcessId->Call();
#### vs.
- Win32::API->Import("kernel32", "int GetCurrentProcessId()");
+ my $UnusedGCPI = Win32::API::More->Import("kernel32", "int GetCurrentProcessId()");
+ die "Failed to import GetCurrentProcessId" if !$UnusedGCPI;
+ $UnusedGCPI->UseMI64(1);
$PID = GetCurrentProcessId();
-Note that C<Import> returns 1 on success and 0 on failure (in which case you
-can check the content of C<$^E>).
+Note that C<Import> returns the Win32::API obj on success and false on failure
+(in which case you can check the content of C<$^E>). This allows some settings
+to be set through method calls that can't be specified as a parameter to Import,
+yet still have the convience of not writing C<-E<gt>Call()>. The Win32::API obj
+does not need to be assigned to a scalar. C<unless(Win32::API::More-E<gt>Import>
+is fine. Prior to v0.76_02, C<Import> returned returned 1 on success and 0 on
+failure.
=head2 IMPORTING A FUNCTION
-You can import a function from a 32 bit Dynamic Link Library (DLL) file
-with the C<new()> function. This will create a Perl object that contains the
-reference to that function, which you can later C<Call()>.
+You can import a function from a 32 bit Dynamic Link Library (DLL) file with
+the C<new()> function or, starting in 0.69, supply your own function pointer.
+This will create a Perl object that contains the reference to that function,
+which you can later C<Call()>.
What you need to know is the prototype of the function you're going to import
(eg. the definition of the function expressed in C syntax).
@@ -461,17 +783,30 @@ one uses Win32::API's internal representation for parameters.
=head2 IMPORTING A FUNCTION BY PROTOTYPE
-You need to pass 2 parameters:
+You need to pass 2 or 3 parameters:
=over 4
=item 1.
-The name of the library from which you want to import the function.
+The name of the library from which you want to import the function. If the
+name is undef, you are requesting a object created from a function pointer,
+and must supply item 2.
=item 2.
-The C prototype of the function.
+This parameter is optional, most people should skip it, skip does not mean
+supplying undef. Supply a function pointer in the format of number 1234, not
+string "\x01\x02\x03\x04". Undef will be returned if the pointer is not
+readable, L<Win32::GetLastError|Win32/Win32::GetLastError()>/L<perlvar/"$^E">
+will be C<ERROR_NOACCESS>.
+
+=item 3.
+
+The C prototype of the function. If you are using a function pointer, the name
+of the function should be something "friendly" to you and no attempt is made
+to retrieve such a name from any DLL's export table. This name for a function
+pointer is also used for Import().
=back
@@ -482,9 +817,15 @@ automatically turned into a C C<NULL> value.
See L<Win32::API::Type> for a list of the known parameter types and
L<Win32::API::Struct> for information on how to define a structure.
+If a prototype type is exactly C<signed char> or C<unsigned char> for an
+"in" parameter or the return parameter, and for "in" parameters only
+C<signed char *> or C<unsigned char *> the parameters will be treated as a
+number, C<0x01>, not C<"\x01">. "UCHAR" is not "unsigned char". Change the
+C prototype if you want numeric handling for your chars.
+
=head2 IMPORTING A FUNCTION WITH A PARAMETER LIST
-You need to pass 4 parameters:
+You need to pass at minimum 4 parameters.
=over 4
@@ -492,17 +833,32 @@ You need to pass 4 parameters:
The name of the library from which you want to import the function.
=item 2.
-The name of the function (as exported by the library).
+This parameter is optional, most people should skip it, skip does not mean
+supplying undef. Supply a function pointer in the format of number C<1234>,
+not string C<"\x01\x02\x03\x04">. Undef will be returned if the pointer is not
+readable, L<Win32::GetLastError|Win32/Win32::GetLastError()>/L<perlvar/"$^E">
+will be C<ERROR_NOACCESS>.
=item 3.
-The number and types of the arguments the function expects as input.
+The name of the function (as exported by the library) or for function pointers
+a name that is "friendly" to you. This name for a function pointer is also used
+for Import(). No attempt is made to retrieve such a name from any DLL's export
+table in the 2nd case.
=item 4.
-The type of the value returned by the function.
+The number and types of the arguments the function expects as input.
=item 5.
+The type of the value returned by the function.
+
+=item 6.
And optionally you can specify the calling convention, this defaults to
-'__stdcall', alternatively you can specify '_cdecl'.
+'__stdcall', alternatively you can specify '_cdecl' or '__cdecl' (API > v0.68)
+or (API > v0.70_02) 'WINAPI', 'NTAPI', 'CALLBACK' (__stdcall), 'WINAPIV' (__cdecl) .
+False is __stdcall. Vararg functions are always cdecl. MS DLLs are typically
+stdcall. Non-MS DLLs are typically cdecl. If API > v0.75, mixing up the calling
+convention on 32 bits is detected and Perl will C<croak> an error message and
+C<die>.
=back
@@ -542,25 +898,36 @@ a couple of directories, including:
=back
-So, you don't have to write F<C:\windows\system\kernel32.dll>;
-only F<kernel32> is enough:
+You may, but don't have to write F<C:\windows\system\kernel32.dll>; or
+F<kernel32.dll>, only F<kernel32> is enough:
- $GetTempPath = new Win32::API('kernel32', ...
+ $GetTempPath = new Win32::API::More('kernel32', ...
=item B<2.>
-Now for the second parameter: the name of the function.
+Since this function is from a DLL, skip the 2nd parameter. Skip does not
+mean supplying undef.
+
+=item B<3.>
+
+Now for the real second parameter: the name of the function.
It must be written exactly as it is exported
-by the library (case is significant here).
+by the library (case is significant here).
If you are using Windows 95 or NT 4.0, you can use the B<Quick View>
command on the DLL file to see the function it exports.
-Remember that you can only import functions from 32 bit DLLs:
+Remember that you can only import functions from 32 or 64 bit DLLs:
in Quick View, the file's characteristics should report
somewhere "32 bit word machine"; as a rule of thumb,
when you see that all the exported functions are in upper case,
-the DLL is a 16 bit one and you can't use it.
+the DLL is a 16 bit one and you can't use it. You also can not load a 32 bit
+DLL into a 64 bit Perl, or vice versa. If you try, C<new>/C<Import> will fail
+and C<$^E> will be C<ERROR_BAD_EXE_FORMAT>.
If their capitalization looks correct, then it's probably a 32 bit
-DLL.
+DLL. If you have Platform SDK or Visual Studio, you can use the Dumpbin
+tool. Call it as C<dumpbin /exports name_of_dll.dll> on the command line.
+If you have Mingw GCC, use objdump as
+C<objdump -x name_of_dll.dll E<gt> dlldump.txt> and search for the word exports
+in the very long output.
Also note that many Win32 APIs are exported twice, with the addition of
a final B<A> or B<W> to their name, for - respectively - the ASCII
@@ -570,11 +937,11 @@ an B<A> to the name and try again; if the extension is built on a
Unicode system, then it will try with the B<W> instead.
So our function name will be:
- $GetTempPath = new Win32::API('kernel32', 'GetTempPath', ...
+ $GetTempPath = new Win32::API::More('kernel32', 'GetTempPath', ...
In our case C<GetTempPath> is really loaded as C<GetTempPathA>.
-=item B<3.>
+=item B<4.>
The third parameter, the input parameter list, specifies how many
arguments the function wants, and their types. It can be passed as
@@ -597,31 +964,98 @@ argument; allowed types are:
=over 4
=item C<I>:
-value is an integer (int)
+value is an unsigned integer (unsigned int)
+
+=item C<i>:
+value is an signed integer (signed int or int)
=item C<N>:
-value is a number (long)
+value is a unsigned pointer sized number (unsigned long)
+
+=item C<n>:
+value is a signed pointer sized number (signed long or long)
+
+=item C<Q>:
+value is a unsigned 64 bit integer number (unsigned long long, unsigned __int64)
+See next item for details.
+
+=item C<q>:
+value is a signed 64 bit integer number (long long, __int64)
+If your perl has 'Q'/'q' quads support for L<perlfunc/pack> then Win32::API's 'q'
+is a normal perl numeric scalar. All 64 bit Perls have quad support. Almost no
+32 bit Perls have quad support. On 32 bit Perls, without quad support,
+Win32::API's 'q'/'Q' letter is a packed 8 byte string. So C<0x8000000050000000>
+from a perl with native Quad support would be written as
+C<"\x00\x00\x00\x50\x00\x00\x00\x80"> on a 32 bit Perl without Quad support.
+To improve the use of 64 bit integers with Win32::API on a 32 bit Perl without
+Quad support, there is a per Win32::API::* object setting called L</UseMI64>
+that causes all quads to be accepted as, and returned as L<Math::Int64> objects.
+For "in" params in Win32::API and Win32::API::More and "out" in
+Win32::API::Callback only, if the argument is a reference, it will automatically
+be treated as a Math::Int64 object without having to previously call
+L</UseMI64>.
=item C<F>:
-value is a floating point number (float)
+value is a single precision (4 bytes) floating point number (float)
=item C<D>:
-value is a double precision number (double)
+value is a double precision (8 bytes) floating point number (double)
+
+=item C<S>:
+value is a unsigned short (unsigned short)
+
+=item C<s>:
+value is a signed short (signed short or short)
=item C<C>:
-value is a char (char)
+value is a char (char), pass as C<"a">, not C<97>, C<"abc"> will truncate to C<"a">
=item C<P>:
value is a pointer (to a string, structure, etc...)
-
-=item C<S>:
-value is a Win32::API::Struct object (see below)
+padding out the buffer string is required, buffer overflow detection is
+performed. Pack and unpack the data yourself. If P is a return type, only
+null terminated strings or NULL pointer are supported. If P is an in type, NULL
+is integer C<0>. C<undef>, C<"0">, and C<""+0> are not integer C<0>, C<"0"+0> is
+integer C<0>.
+
+It is suggested to
+not use P as a return type and instead use N and read the memory yourself, and
+free the pointer if applicable. This pointer is effectively undefined after the
+C function returns control to Perl. The C function may not hold onto it after
+the C function returns control. There are exceptions where the pointer will
+remain valid after the C function returns control, but tread at your own risk,
+and at your knowledge of Perl interpreter's C internals.
+
+=item C<T>:
+value is a Win32::API::Struct object, in parameter only, pass by reference
+(pointer) only, pass by copy not implemented, see other sections for more
=item C<K>:
-value is a Win32::API::Callback object (see L<Win32::API::Callback>)
+value is a Win32::API::Callback object, in parameter only, (see L<Win32::API::Callback>)
+
+=item C<V>:
+no value, no parameters, stands for C<void>, may not be combined with any other
+letters, equivalent to a ""
=back
+For beginners, just skip this paragraph.
+Note, all parameter types are little endian. This is probably what you want
+unless the documentation for the C function you are calling explicitly says
+the parameters must be big endian. If there is no documentation for your C
+function or no mention of endianess in the documentation, this doesn't apply
+to you and skip the rest of this paragraph. There is no inherent support
+for big endian parameters. Perl's scalar numbers model is that numeric
+scalars are effectively opaque and their machine representation is
+irrelevant. On Windows Perl, scalar numbers are little endian
+internally. So C<$number = 5; print "$number";> will put 5 on the screen.
+C<$number> given to Win32::API will pass little endian integer 5 to the C
+function call. This is almost surly what you want. If you really must pass
+a big endian integer, do C<$number = unpack('L', pack('N', 5));>, then
+C<print "$number";> will put 83886080 on the screen, but this is big endian 5,
+and passing 83886080 to C<-E<gt>Call()> will make sure that
+the C function is getting big endian 5. See L<perlpacktut> for more.
+
Our function needs two parameters: a number (C<DWORD>) and a pointer to a
string (C<LPSTR>):
@@ -629,24 +1063,32 @@ string (C<LPSTR>):
=item B<4.>
-The fourth and final parameter is the type of the value returned by the
+The fourth is the type of the value returned by the
function. It can be one of the types seen above, plus another type named B<V>
(for C<void>), used for functions that do not return a value.
-In our example the value returned by GetTempPath() is a C<DWORD>, so
-our return type will be B<N>:
+In our example the value returned by GetTempPath() is a C<DWORD>, which is a
+typedef for unsigned long, so our return type will be B<N>:
- $GetTempPath = new Win32::API('kernel32', 'GetTempPath', 'NP', 'N');
+ $GetTempPath = new Win32::API::More('kernel32', 'GetTempPath', 'NP', 'N');
Now the line is complete, and the GetTempPath() API is ready to be used
in Perl. Before calling it, you should test that $GetTempPath is
-C<defined>, otherwise either the function or the library could not be
-loaded; in this case, C<$!> will be set to the error message reported
-by Windows.
+L<perlfunc/defined>, otherwise errors such as the function or the library could
+not be loaded or the C prototype was unparsable happened, and no object was
+created. If the return value is undefined, to get detailed error status, use
+L<perlvar/"$^E"> or L<Win32::GetLastError|Win32/Win32::GetLastError()>. C<$^E>
+is slower than C<Win32::GetLastError> and useless on Cygwin, but C<$^E> in
+string context provides a readable description of the error. In numeric context,
+C<$^E> is equivelent to C<Win32::GetLastError>. C<Win32::GetLastError> always
+returns an integer error code. You may use
+L<Win32::FormatMessage|Win32/Win32::FormatMessage()> to convert an integer error
+code to a readable description on Cygwin and Native builds of Perl.
+
Our definition, with error checking added, should then look like this:
- $GetTempPath = new Win32::API('kernel32', 'GetTempPath', 'NP', 'N');
+ $GetTempPath = new Win32::API::More('kernel32', 'GetTempPath', 'NP', 'N');
if(not defined $GetTempPath) {
- die "Can't import API GetTempPath: $!\n";
+ die "Can't import API GetTempPath: $^E\n";
}
=back
@@ -668,10 +1110,9 @@ Perl will C<croak> an error message and C<die>.
The two parameters needed here are the length of the buffer
that will hold the returned temporary path, and a pointer to the
buffer itself.
-For numerical parameters, you can use either a constant expression
-or a variable, while B<for pointers you must use a variable name> (no
-Perl references, just a plain variable name).
-Also note that B<memory must be allocated before calling the function>,
+For numerical parameters except for char, you can use either a constant expression
+or a variable, it will be numified similar to the expression C<($var+0)>.
+For pointers, also note that B<memory must be allocated before calling the function>,
just like in C.
For example, to pass a buffer of 80 characters to GetTempPath(),
it must be initialized before with:
@@ -679,14 +1120,14 @@ it must be initialized before with:
$lpBuffer = " " x 80;
This allocates a string of 80 characters. If you don't do so, you'll
-probably get C<Runtime exception> errors, and generally nothing will
-work. The call should therefore include:
+probably get a fatal buffer overflow error starting in 0.69.
+The call should therefore include:
$lpBuffer = " " x 80;
$GetTempPath->Call(80, $lpBuffer);
And the result will be stored in the $lpBuffer variable.
-Note that you don't need to pass a reference to the variable
+Note that you never need to pass a reference to the variable
(eg. you B<don't need> C<\$lpBuffer>), even if its value will be set
by the function.
@@ -746,10 +1187,17 @@ them as parameters to Win32::API functions. A short example follows:
print "The cursor is at: $pt->{x}, $pt->{y}\n";
Note that this works only when the function wants a
-B<pointer to a structure>: as you can see, our structure is named
-'POINT', but the API used 'LPPOINT'. 'LP' is automatically added at
-the beginning of the structure name when feeding it to a Win32::API
-call.
+B<pointer to a structure>, not a "pass by copy" structure. As you can see, our
+structure is named 'POINT', but the API used 'LPPOINT'. Some heuristics are
+done to validate the argument's type vs the parameter's type if the function
+has a C prototype definition (not letter definition). First, if the parameter
+type starts with the LP prefix, the LP prefix is stripped, then compared to
+the argument's type. If that fails, the Win32::API::Type database
+(see L<Win32::API::Type/typedef>)
+will be used to convert the parameter type to the base type. If that fails,
+the parameter type will be stripped of a trailing whitespace then a '*', and
+then checked against the base type. L<Dies|perlfunc/die> if the parameter and
+argument types do not match after 3 attempts.
For more information, see also L<Win32::API::Struct>.
@@ -760,20 +1208,231 @@ you can still use the low-level approach to use structures:
=item 1.
-you have to pack() the required elements in a variable:
+you have to L<pack()|perlfunc/pack> the required elements in a variable:
- $lpPoint = pack('LL', 0, 0); # store two LONGs
+ $lpPoint = pack('ll', 0, 0); # store two LONGs
=item 2.
-to access the values stored in a structure, unpack() it as required:
+to access the values stored in a structure, L<unpack()|perlfunc/unpack> it as required:
- ($x, $y) = unpack('LL', $lpPoint); # get the actual values
+ ($x, $y) = unpack(';;', $lpPoint); # get the actual values
=back
The rest is left as an exercise to the reader...
+=head2 EXPORTED FUNCTIONS
+
+=head3 ReadMemory
+
+ $copy_of_memblock = ReadMemory($SourcePtr, $length);
+
+Reads the source pointer for C<$length> number of bytes. Returns a copy of
+the memory block in a scalar. No readability checking is done on C<$SourcePtr>.
+C<$SourcePtr>'s format is 123456, not C<"\x01\x02\x03\x04">.
+
+=head3 WriteMemory
+
+ WriteMemory($DestPtr, $sourceScalar, $length);
+
+Copies the string contents of the C<$sourceScalar> scalar to C<$DestPtr> for
+C<$length> bytes. $length must be less than or equal to the length of
+C<$sourceScalar>, otherwise the function croaks. No readability checking is
+done on C<$DestPtr>. C<$DestPtr>'s format is 123456, not
+C<"\x01\x02\x03\x04">. Returns nothing.
+
+=head3 MoveMemory
+
+ MoveMemory($destPtr, $sourcePtr, $length);
+
+Copies a block of memory from one location to another. The source and
+destination blocks may overlap. All pointers are in the format of 123456,
+not C<"\x01\x02\x03\x04">. No readability checking is done. Returns nothing.
+
+=head3 IsBadReadPtr
+
+ if(IsBadReadPtr($ptr, $length)) {die "bad ptr";}
+
+Probes a memory block for C<$length> bytes for readability. Returns true if
+access violation occurs, otherwise false is returned. This function is useful
+to avoid dereferencing pointers which will crash the perl process. This function
+has many limitations, including not detecting uninitialized memory, not
+detecting freed memory, and not detecting gibberish. It can not tell whether a
+function pointer is valid x86 machine code. Ideally, you should never use it,
+or remove it once your code is stable. C<$ptr> is in the format of 123456,
+not C<"\x01\x02\x03\x04">. See MS's documentation for a lot more
+on this function of the same name.
+
+=head3 SafeReadWideCString
+
+ $source = Encode::encode("UTF-16LE","Just another perl h\x{00E2}cker\x00");
+ $string = SafeReadWideCString(unpack('J',pack('p', $source)));
+ die "impossible" if $source ne "Just another perl h\x{00E2}cker";
+
+Safely (SEH aware) reads a utf-16 wide null terminated string (the first and
+only parameter), into a scalar. Returns undef, if an access violation happens
+or null pointer (same thing). The string pointer is in the format of 123456,
+not C<"\x01\x02\x03\x04">. The returned scalar will be UTF8 marked if the string
+can not be represented in the system's ANSI codepage. Conversion is done with
+WideCharToMultiByte. Returns a 0 length scalar string if WideCharToMultiByte fails.
+This function was created because L<pack's|perlfunc/pack> p letter won't read UTF16
+and L</ReadMemory> and L</IsBadReadPtr> require an explicit length.
+
+=head2 CONSTRUCTORS
+
+=head3 new
+
+ $obj = Win32::API::More->new([$dllname | (undef , $funcptr)], [$c_proto | ($in, $out [, $calling_convention])]);
+
+See L</DESCRIPTION>.
+
+=head3 Import
+ $obj = Win32::API::More->Import([$dllname | (undef , $funcptr)], [$c_proto | ($in, $out [, $calling_convention])]);
+
+See L</DESCRIPTION>.
+
+=head2 METHODS
+
+=head3 Call
+
+The main method of a Win32::API object. Documented elsewhere in this document.
+
+=head3 UseMI64
+
+ $bool = $APIObj->UseMI64();
+ $oldbool = $APIObj->UseMI64($newbool);
+
+Turns on Quads as L<Math::Int64> objects support for a particular object
+instance. You must call L<perlfunc/use>/L<perlfunc/require> on Math::Int64
+before calling UseMI64. Win32::API does not C<use> Math::Int64 for you.
+Works on Win32::API and Win32::API::Callback objects. This method
+does not exist if your Perl natively supports Quads (64 bit Perl for example).
+Takes 1 optional parameter, which is a true or false value to use or don't use
+Math::Int64, returns the old setting, which is a true or false value. If called
+without any parameters, returns current setting, which is a true or false value,
+without setting the option. As discussed in L</q>, if you are not using
+Math::Int64 you must supply/will receive 8 byte scalar strings for quads.
+For "in" params in Win32::API and Win32::API::More and "out" in
+Win32::API::Callback only, if the argument is a reference, it will automatically
+be treated as a Math::Int64 object without having to previously call this
+function.
+
+=head2 VERBOSE DEBUGGING
+
+If using C<Win32::GetLastError> and C<$^E> does not reveal the problem with your
+use of Win32::API, you may turn on Win32::API's very verbose debugging mode as
+follows
+
+ BEGIN {
+ $Win32::API::DEBUG = 1;
+ }
+ use Win32::API;
+ $function = Win32::API::More->new(
+ 'mydll', 'int sum_integers(int a, int b)'
+ );
+
+=head1 HISTORY
+
+=over 4
+
+=item UseMI64 API change
+
+Starting in 0.71, UseMI64 on a set returns old value, not previously
+new value.
+
+=item fork safe
+
+Starting in 0.71, a Win32::API object can go through a fork and work
+correctly in the child and parent psuedo-processes. Previously when either
+psuedo-processes exited, the DLL would be unloaded and the other
+psuedo-processes would crash if a Call() was done on the object.
+
+=item return value signedness
+
+Prior to 0.69, for numeric integer types, the return scalar was always signed.
+Unsigned-ness was ignored.
+
+=item shorts
+
+Prior to 0.69, shorts were not supported. 'S' meant a sturct. To fix this
+Win32::API::More class was created for 0.69. 'S'/'s' now means short, per pack's
+letters. Struct has been moved to letter 'T'. Win32::API will continue to exist
+for legacy code.
+
+=item float return types
+
+Prior to 0.69, if a function had a return type of float, it was silently
+not called.
+
+=item buffer overflow protection
+
+Introduced in 0.69. If disabling is required, which is highly
+B<not recommended>, set an environmental variable called
+WIN32_API_SORRY_I_WAS_AN_IDIOT to 1.
+
+=item automatic un/pack
+
+Starting with 0.69, when using Win32::API::More, there is automatic un/packing
+of pointers to numbers-ish things for in parameters when using the C
+prototype interface.
+
+=item Quads on 32 bit
+
+Added in 0.70.
+
+=item __stdcall vs __cdecl checking on 32 bits
+
+Added in 0.76_01
+
+=item Import returns an api obj on success, undef on failure, instead of 1 or 0
+
+Added in 0.76_02
+
+=item checking C<$!> for C<new>/C<Import> failure is broken and deprecated
+
+Starting in 0.76_06, due to many bugs with C<new> and C<Import> not setting
+L<perlvar/$!> or Win32 and C error codes overlapping and Win32 error codes being
+stringified as different C error codes, checking C<$!> is deprecated and the
+existing, partial setting of C<$!>, maybe removed in the future. Only check
+C<Win32::GetLastError()> or C<$^E> to find out why the call failed.
+
+=back
+
+See the C<Changes> file for more details, many of which not mentioned here.
+
+=head1 BUGS AND LIMITATIONS
+
+=over 4
+
+=item E<nbsp> Unicode DLL paths
+
+Untested.
+
+=item E<nbsp> ithreads
+
+Minimally tested.
+
+=item E<nbsp> C functions getting utf8 scalars vs byte scalars
+
+Untested and undefined.
+
+=back
+
+=head1 SEE ALSO
+
+L<Math::Int64>
+
+L<Win32::API::Struct>
+
+L<Win32::API::Type>
+
+L<Win32::API::Callback>
+
+L<Win32::API::Callback::IATPatch>
+
+L<http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/function-calling-conventions.html>
+
=head1 AUTHOR
Aldo Calpini ( I<dada@perl.it> ).
@@ -782,6 +1441,10 @@ Aldo Calpini ( I<dada@perl.it> ).
Cosimo Streppone ( I<cosimo@cpan.org> )
+=head1 MAJOR CONTRIBUTOR
+
+Daniel Dragan ( I<bulkdd@cpan.org> )
+
=head1 LICENSE
To finally clarify this, C<Win32::API> is OSI-approved free software;
@@ -795,7 +1458,7 @@ See L<http://dev.perl.org/licenses/artistic.html>
All the credits go to Andrea Frosini for the neat assembler trick
that makes this thing work. I've also used some work by Dave Roth
for the prototyping stuff. A big thank you also to Gurusamy Sarathy
-for his unvaluable help in XS development, and to all the Perl
+for his invaluable help in XS development, and to all the Perl
community for being what it is.
Cosimo also wants to personally thank everyone that contributed
diff --git a/Master/tlpkg/tlperl/lib/Win32/API/Callback.pm b/Master/tlpkg/tlperl/lib/Win32/API/Callback.pm
index 46879b4041b..b96d938265e 100644
--- a/Master/tlpkg/tlperl/lib/Win32/API/Callback.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/API/Callback.pm
@@ -6,17 +6,23 @@
# Win32::API::Callback - Perl Win32 API Import Facility
#
# Author: Aldo Calpini <dada@perl.it>
+# Author: Daniel Dragan <bulkdd@cpan.org>
# Maintainer: Cosimo Streppone <cosimo@cpan.org>
#
#######################################################################
package Win32::API::Callback;
+use strict;
+use warnings;
+use vars qw( $VERSION @ISA $Stage2FuncPtrPkd );
+
+$VERSION = '0.77';
-$VERSION = '0.68';
require Exporter; # to export the constants to the main:: space
require DynaLoader; # to dynuhlode the module.
@ISA = qw( Exporter DynaLoader );
+#use Data::Dumper;
sub DEBUG {
if ($WIN32::API::DEBUG) {
@@ -27,39 +33,32 @@ sub DEBUG {
}
}
-use Win32::API;
+use Win32::API qw ( WriteMemory ) ;
use Win32::API::Type;
-use Win32::API::Struct;
-
-#######################################################################
-# This AUTOLOAD is used to 'autoload' constants from the constant()
-# XS function. If a constant is not found then control is passed
-# to the AUTOLOAD in AutoLoader.
-#
-
-sub AUTOLOAD {
- my ($constname);
- ($constname = $AUTOLOAD) =~ s/.*:://;
-
- #reset $! to zero to reset any current errors.
- $! = 0;
- my $val = constant($constname, @_ ? $_[0] : 0);
- if ($! != 0) {
- if ($! =~ /Invalid/) {
- $AutoLoader::AUTOLOAD = $AUTOLOAD;
- goto &AutoLoader::AUTOLOAD;
- }
- else {
- ($pack, $file, $line) = caller;
- die
- "Your vendor has not defined Win32::API::Callback macro $constname, used at $file line $line.";
- }
+use Config;
+#use Win32::API::Struct; #not implemented
+
+
+BEGIN {
+ #there is supposed to be 64 bit IVs on 32 bit perl compatibility here
+ #but it is untested
+ #Win64 added in 5.7.3
+ eval "sub IVSIZE () { ".length(pack($] >= 5.007003 ? 'J' : 'I' ,0))." }";
+ #what kind of stack processing/calling convention/machine code we needed
+ eval "sub ISX64 () { ".(Win32::API::PTRSIZE() == 8 ? 1 : 0)." }";
+ eval 'sub OPV () {'.$].'}';
+ sub OPV();
+ sub CONTEXT_XMM0();
+ sub CONTEXT_RAX();
+ *IsBadStringPtr = *Win32::API::IsBadStringPtr;
+ sub PTRSIZE ();
+ *PTRSIZE = *Win32::API::PTRSIZE;
+ sub PTRLET ();
+ *PTRLET = *Win32::API::Type::pointer_pack_type;
+ if(OPV <= 5.008000){ #don't have unpackstring in C
+ eval('sub _CallUnpack {return unpack($_[0], $_[1]);}');
}
- eval "sub $AUTOLOAD { $val }";
- goto &$AUTOLOAD;
}
-
-
#######################################################################
# dynamically load in the API extension module.
#
@@ -69,41 +68,44 @@ bootstrap Win32::API::Callback;
# PUBLIC METHODS
#
sub new {
- my ($class, $proc, $in, $out) = @_;
- my %self = ();
-
+ my ($class, $proc, $in, $out, $callconvention) = @_;
+ my $self = bless {}, $class; #about croak/die safety, can safely bless here,
+ #a ::Callback has no DESTROY, it has no resources to release, there is a HeapBlock obj
+ #stored in the ::Callback hash, but the HeapBlock destroys on its own
# printf "(PM)Callback::new: got proc='%s', in='%s', out='%s'\n", $proc, $in, $out;
- $self{in} = [];
+ $self->{intypes} = []; #XS requires this, do not remove
if (ref($in) eq 'ARRAY') {
foreach (@$in) {
- push(@{$self{in}}, Win32::API::type_to_num($_));
+ push(@{$self->{intypes}}, $_);
}
}
else {
my @in = split '', $in;
foreach (@in) {
- push(@{$self{in}}, Win32::API::type_to_num($_));
+ push(@{$self->{intypes}}, $_);
+ }
+ }
+ $self->{inbytes} = 0;
+ foreach(@{$self->{intypes}}){ #calc how long the c stack is
+ if($_ eq 'Q' or $_ eq 'q' or $_ eq 'D' or $_ eq 'd'){
+ $self->{inbytes} += 8; #always 8
+ }
+ else{
+ $self->{inbytes} += PTRSIZE; #4 or 8
}
}
- $self{out} = Win32::API::type_to_num($out);
- $self{sub} = $proc;
- my $self = bless \%self, $class;
+ $self->{outtype} = $out;
+ $self->{out} = Win32::API->type_to_num($out);
+ $self->{sub} = $proc;
+ $self->{cdecl} = Win32::API::calltype_to_num($callconvention);
DEBUG "(PM)Callback::new: calling CallbackCreate($self)...\n";
- my $hproc = CallbackCreate($self);
+ my $hproc = MakeCB($self);
DEBUG "(PM)Callback::new: hproc=$hproc\n";
- #### ...if that fails, set $! accordingly
- if (!$hproc) {
- $! = Win32::GetLastError();
- return undef;
- }
-
- #### ok, let's stuff the object
$self->{code} = $hproc;
- $self->{sub} = $proc;
#### cast the spell
return $self;
@@ -117,6 +119,309 @@ sub MakeStruct {
return $struct;
}
+#this was rewritten in XS, and is broken b/c it doesn't work on 32bit Perl with Quads
+#sub MakeParamArr { #on x64, never do "$i++; $packedparam .= $arr->[$i];"
+# #on x86, structs and over word size params appears on the stack,
+# #on x64 anything over the size of a "word" is passed by pointer
+# #nothing takes more than 8 bytes per parameter on x64
+# #there is no way to formally specify a pass by copy struct in ::Callback
+# #this only matters on x86, a work around is a bunch of N/I parameters,
+# #repack them as Js, then concat them, and you have the original pass by copy
+# #x86 struct
+# my ($self, $arr) = @_;
+# my ($i, @pass_arr) = (0);
+# for(@{$self->{intypes}}){ #elements of intypes are not 1 to 1 with stack params
+# my ($typeletter, $packedparam, $finalParam, $unpackletter) = ($_, $arr->[$i]);
+#
+# #structs don't work, this is broken code from old version
+# #$self->{intypes} is letters types not C prototype params
+# #C prototype support would have to exist for MakeStruct to work
+# if( $typeletter eq 'S' || $typeletter eq 's'){
+# die "Win32::API::Callback::MakeParamArr type letter \"S\" and struct support not implemented";
+# #push(@pass_arr, MakeStruct($self, $i, $packedparam));
+# }elsif($typeletter eq 'I'){
+# $unpackletter = 'I', goto UNPACK;
+# }elsif($typeletter eq 'i'){
+# $unpackletter = 'i', goto UNPACK;
+# }elsif($typeletter eq 'f' || $typeletter eq 'F'){
+# $unpackletter = 'f', goto UNPACK;
+# }
+# elsif($typeletter eq 'd' || $typeletter eq 'D'){
+# if(IVSIZE == 4){ #need more data, 32 bit machine
+# $packedparam .= $arr->[++$i];
+# }
+# $unpackletter = 'd', goto UNPACK;
+# }
+# elsif($typeletter eq 'N' || $typeletter eq 'L' #on x64, J is 8 bytes
+# || (IVSIZE == 8 ? $typeletter eq 'Q': 0)){
+# $unpackletter = 'J', goto UNPACK;
+# }elsif($typeletter eq 'n' || $typeletter eq 'l'
+# || (IVSIZE == 8 ? $typeletter eq 'q': 0)){
+# $unpackletter = 'j', goto UNPACK;
+# }elsif(IVSIZE == 4 && ($typeletter eq 'q' || $typeletter eq 'Q')){
+# #need more data, 32 bit machine
+# $finalParam = $packedparam . $arr->[++$i];
+# }elsif($typeletter eq 'p' || $typeletter eq 'P'){
+# if(!IsBadStringPtr($arr->[$i], ~0)){ #P letter is terrible design
+# $unpackletter = 'p', goto UNPACK;
+# }#else undef
+# }
+# else{ die "Win32::API::Callback::MakeParamArr unknown in type letter $typeletter";}
+# goto GOTPARAM;
+# UNPACK:
+# $finalParam = unpack($unpackletter, $packedparam);
+# GOTPARAM:
+# $i++;
+# push(@pass_arr, $finalParam);
+# }
+# return \@pass_arr;
+#}
+
+#on x64
+#void RunCB($self, $EBP_ESP, $retval)
+#on x86
+#void RunCB($self, $EBP_ESP, $retval, $unwindcount, $F_or_D)
+if(! ISX64 ) {
+*RunCB = sub {#32 bits
+ my $self = $_[0];
+ my (@pass_arr, $return, $typeletter, $inbytes, @arr);
+ $inbytes = $self->{inbytes};
+ #first is ebp copy then ret address
+ $inbytes += PTRSIZE * 2;
+ my $paramcount = $inbytes / PTRSIZE ;
+ my $stackstr = unpack('P'.$inbytes, pack(PTRLET, $_[1]));
+ #pack () were added in 5.7.2
+ if (OPV > 5.007002) {
+ @arr = unpack("(a[".PTRLET."])[$paramcount]",$stackstr);
+ } else {
+ #letter can not be used for size, must be numeric on 5.6
+ @arr = unpack(("a4") x $paramcount,$stackstr);
+ }
+ shift @arr, shift @arr; #remove ebp copy and ret address
+ $paramcount -= 2;
+ $return = &{$self->{sub}}(@{MakeParamArr($self, \@arr)});
+
+ #now the return type
+ $typeletter = $self->{outtype};
+ #float_or_double flag, its always used
+ #float is default for faster copy of probably unused value
+ $_[4] = 0;
+ #its all the same in memory
+ if($typeletter eq 'n' || $typeletter eq 'N'
+ || $typeletter eq 'l' || $typeletter eq 'L'
+ || $typeletter eq 'i' || $typeletter eq 'I'){
+ $_[2] = pack(PTRLET, $return);
+ }elsif($typeletter eq 'q' || $typeletter eq 'Q'){
+ if(IVSIZE == 4){
+ if($self->{'UseMI64'} || ref($return)){ #un/signed meaningless
+ $_[2] = Math::Int64::int64_to_native($return);
+ }
+ else{
+ warn("Win32::API::Callback::RunCB return value for return type Q is under 8 bytes long")
+ if length($return) < 8;
+ $_[2] = $return.''; #$return should be a 8 byte string
+ #will be garbage padded in XS if < 8, but must be a string, not a IV or under
+ }
+ }
+ else{
+ $_[2] = pack($typeletter, $return);
+ }
+ }elsif($typeletter eq 'f' || $typeletter eq 'F' ){
+ $_[2] = pack('f', $return);
+ }elsif($typeletter eq 'd' || $typeletter eq 'D' ){
+ $_[2] = pack('d', $return);
+ $_[4] = 1; #use double
+ }else { #return null
+ $_[2] = "\x00" x 8;
+ }
+
+ if(! $self->{cdecl}){
+ $_[3] = PTRSIZE * $paramcount; #stack rewind amount in bytes
+ }
+ else{$_[3] = 0;}
+};
+}
+else{ #64 bits
+*RunCB = sub {
+ my $self = $_[0];
+ my (@pass_arr, $return, $typeletter);
+ my $paramcount = $self->{inbytes} / IVSIZE;
+ my $stack_ptr = unpack('P[J]', pack('J', ($_[1]+CONTEXT_RAX())));
+ my $stack_str = unpack('P['.$self->{inbytes}.']', $stack_ptr);
+ my @stack_arr = unpack("(a[J])[$paramcount]",$stack_str);
+ #not very efficient, todo search for f/F/d/D in new() not here
+ my $XMMStr = unpack('P['.(4 * 16).']', pack('J', ($_[1]+CONTEXT_XMM0())));
+ #print Dumper([unpack('(H[32])[4]', $XMMStr)]);
+ my @XMM = unpack('(a[16])[4]', $XMMStr);
+ #assume registers are copied to shadow stack space already
+ #because of ... prototype, so only XMM registers need to be fetched.
+ #Limitation, vararg funcs on x64 get floating points in normal registers
+ #not XMMs, so a vararg function taking floats and doubles in the first 4
+ #parameters isn't supported
+ if($paramcount){
+ for(0..($paramcount > 4 ? 4 : $paramcount)-1){
+ my $typeletter = ${$self->{intypes}}[$_];
+ if($typeletter eq 'f' || $typeletter eq 'F' || $typeletter eq 'd'
+ || $typeletter eq 'D'){
+ #x64 calling convention does not use the high 64 bits of a XMM register
+ #although right here the high 64 bits are in @XMM elements
+ #J on x64 is 8 bytes, a double will not corrupt, this is unreachable on x86
+ #note we are copying 16 bytes elements to @stack_arr, @stack_arr is
+ #normally 8 byte elements, unpack ignores the excess bytes later
+ $stack_arr[$_] = $XMM[$_];
+ }
+ }
+ }
+ #print Dumper(\@stack_arr);
+ #print Dumper(\@XMM);
+ $return = &{$self->{sub}}(@{MakeParamArr($self, \@stack_arr)});
+
+ #now the return type
+ $typeletter = $self->{outtype};
+ #its all the same in memory
+ if($typeletter eq 'n' || $typeletter eq 'N'
+ || $typeletter eq 'l' || $typeletter eq 'L'
+ || $typeletter eq 'i' || $typeletter eq 'I'
+ || $typeletter eq 'q' || $typeletter eq 'Q'){
+ $_[2] = pack('J', $return);
+ }
+ elsif($typeletter eq 'f' || $typeletter eq 'F' ){
+ $_[2] = pack('f', $return);
+ }
+ elsif($typeletter eq 'd' || $typeletter eq 'D' ){
+ $_[2] = pack('d', $return);
+ }
+ else { #return null
+ $_[2] = pack('J', 0);
+ }
+};
+}
+
+sub MakeCB{
+
+ my $self = $_[0];
+ #this x86 function does not corrupt the callstack in a debugger since it
+ #uses ebp and saves ebp on the stack, the function won't have a pretty
+ #name though
+ my $code = (!ISX64) ? ('' #parenthesis required to constant fold
+ ."\x55" # push ebp
+ ."\x8B\xEC" # mov ebp, esp
+ ."\x83\xEC\x0C"# sub esp, 0Ch
+ ."\x8D\x45\xFC" # lea eax, [ebp+FuncRtnCxtVar]
+ ."\x50"# push eax
+ ."\x8D\x45\xF4"# lea eax, [ebp+retval]
+ ."\x50"# push eax
+ ."\x8B\xC5"# mov eax,ebp
+ ."\x50"# push eax
+ ."\xB8").PackedRVTarget($self)#B8 mov imm32 to eax, a HV * winds up here
+ .("\x50"# push eax
+ ."\xB8").$Stage2FuncPtrPkd # mov eax, 0C0DE0001h
+ .("\xFF\xD0"# call eax
+ #since ST(0) is volatile, we don't care if we fill it with garbage
+ ."\x80\x7D\xFE\x00"#cmp [ebp+FuncRtnCxtVar.F_Or_D], 0
+ ."\x74\x05"# jz 5 bytes
+ ."\xDD\x45\xF4"# fld qword ptr [ebp+retval] (double)
+ ."\xEB\x03"# jmp 3 bytes
+ ."\xD9\x45\xF4"# fld dword ptr [ebp+retval] (float)
+ #rewind sp to entry sp, no pop push after this point
+ ."\x83\xC4\x24"# add esp, 24h
+ ."\x8B\x45\xF4"# mov eax, dword ptr [ebp+retval]
+ #edx might be garbage, we don't care, caller only looks at volatile
+ #registers that the caller's prototype says the caller does
+ ."\x8B\x55\xF8"# mov edx, dword ptr [ebp+retval+4]
+ #can't use retn op, it requires a immediate count, our count is in a register
+ #only one register available now, this will be complicated
+ ."\x0F\xB7\x4D\xFC"#movzx ecx, word ptr [ebp+FuncRtnCxtVar.unwind_len]
+ ."\x01\xCC"# add esp, ecx , might be zero or more
+ ."\x8B\x4D\x04"# mov ecx, dword ptr [ebp+4] ret address
+ ."\x8B\x6D\x00"# mov ebp, dword ptr [ebp+0] restore BP
+ ."\xFF\xE1")# jmp ecx
+
+
+ #begin x64 part
+ #these packs don't constant fold in < 5.17 :-(
+ #they are here for readability
+ :(''.pack('C', 0b01000000 #REX base
+ | 0b00001000 #REX.W
+ | 0b00000001 #REX.B
+ ).pack('C', 0xB8+2) #mov to r10 register
+ .PackedRVTarget($self)
+ .pack('C', 0b01000000 #REX base
+ | 0b00001000 #REX.W
+ ).pack('C', 0xB8) #mov to rax register
+ .$Stage2FuncPtrPkd
+ ."\xFF\xE0");# jmp rax
+#making a full function in Perl in x64 was removed because RtlAddFunctionTable
+#has no effect on VS 2008 debugger, it is a bug in VS 2008, in WinDbg the C callstack
+#is correct with RtlAddFunctionTable, and broken without RtlAddFunctionTable
+#in VS 2008, the C callstack was always broken since WinDbg and VS 2008 both
+#*only* use Unwind Tables on x64 to calculate C callstacks, they do not, I think,
+#use 32 bit style EBP/RBP walking, x64 VC almost never uses BP addressing anyway.
+#The easiest fix was to not have dynamic machine code in the callstack at all,
+#which is what I did. Having good C callstacks in a debugger with ::API and
+#::Callback are a good goal.
+#
+##--- c:\documents and settings\administrator\desktop\w32api\callback\callback.c -
+# $code .= "\x4C\x8B\xDC";# mov r11,rsp
+# $code .= "\x49\x89\x4B\x08";# mov qword ptr [r11+8],rcx
+# $code .= "\x49\x89\x53\x10";# mov qword ptr [r11+10h],rdx
+# $code .= "\x4D\x89\x43\x18";# mov qword ptr [r11+18h],r8
+# $code .= "\x4D\x89\x4B\x20";# mov qword ptr [r11+20h],r9
+# $code .= "\x48\x83\xEC\x78";# sub rsp,78h
+# #void (*LPerlCallback)(SV *, void *, unsigned __int64 *, void *) =
+# #( void (*)(SV *, void *, unsigned __int64 *, void *)) 0xC0DE00FFFF000001;
+# #__m128 arr [4];
+# #__m128 retval;
+## arr[0].m128_u64[0] = 0xFFFF00000000FF10;
+##00000000022D1017 48 B8 10 FF 00 00 00 00 FF FF mov rax,0FFFF00000000FF10h
+##arr[0].m128_u64[1] = 0xFFFF00000000FF11;
+## arr[1].m128_u64[0] = 0xFFFF00000000FF20;
+## arr[1].m128_u64[1] = 0xFFFF00000000FF21;
+## arr[2].m128_u64[0] = 0xFFFF00000000FF30;
+## arr[2].m128_u64[1] = 0xFFFF00000000FF31;
+## arr[3].m128_u64[0] = 0xFFFF00000000FF40;
+## arr[3].m128_u64[1] = 0xFFFF00000000FF41;
+#
+## LPerlCallback((SV *)0xC0DE00FFFF000002, (void*) arr, (unsigned __int64 *)&retval,
+## (DWORD_PTR)&a);
+##00000000022D1021 4D 8D 4B 08 lea r9,[r11+8] #no 4th param
+# $code .= "\x4D\x8D\x43\xA8";# lea r8,[r11-58h] #&retval param
+##00000000022D1029 49 89 43 B8 mov qword ptr [r11-48h],rax
+##00000000022D102D 48 B8 11 FF 00 00 00 00 FF FF mov rax,0FFFF00000000FF11h
+# $code .= "\x49\x8D\x53\xB8";# lea rdx,[r11-48h] #arr param
+##00000000022D103B 49 89 43 C0 mov qword ptr [r11-40h],rax
+##00000000022D103F 48 B8 20 FF 00 00 00 00 FF FF mov rax,0FFFF00000000FF20h
+##00000000022D1049 48 B9 02 00 00 FF FF 00 DE C0 mov rcx,0C0DE00FFFF000002h
+# $code .= "\x48\xB9".PackedRVTarget($self);# mov rcx, the HV *
+##00000000022D1053 49 89 43 C8 mov qword ptr [r11-38h],rax
+##00000000022D1057 48 B8 21 FF 00 00 00 00 FF FF mov rax,0FFFF00000000FF21h
+##00000000022D1061 49 89 43 D0 mov qword ptr [r11-30h],rax
+##00000000022D1065 48 B8 30 FF 00 00 00 00 FF FF mov rax,0FFFF00000000FF30h
+##00000000022D106F 49 89 43 D8 mov qword ptr [r11-28h],rax
+##00000000022D1073 48 B8 31 FF 00 00 00 00 FF FF mov rax,0FFFF00000000FF31h
+##00000000022D107D 49 89 43 E0 mov qword ptr [r11-20h],rax
+##00000000022D1081 48 B8 40 FF 00 00 00 00 FF FF mov rax,0FFFF00000000FF40h
+##00000000022D108B 49 89 43 E8 mov qword ptr [r11-18h],rax
+##00000000022D108F 48 B8 41 FF 00 00 00 00 FF FF mov rax,0FFFF00000000FF41h
+##00000000022D1099 49 89 43 F0 mov qword ptr [r11-10h],rax
+##00000000022D109D 48 B8 01 00 00 FF FF 00 DE C0 mov rax,0C0DE00FFFF000001h
+# $code .= "\x48\xB8".$Stage2FuncPtrPkd; # mov rax,0C0DE00FFFF000001h
+# $code .= "\xFF\xD0";# call rax
+## return *(void **)&retval;
+# $code .= "\x48\x8B\x44\x24\x20";# mov rax,qword ptr [retval]
+##}
+# $code .= "\x48\x83\xC4\x78";# add rsp,78h
+# $code .= "\xC3";# ret
+
+#$self->{codestr} = $code; #save memory
+#32 bit perl doesn't use DEP in my testing, but use executable heap to be safe
+#a Win32::API::Callback::HeapBlock is a ref to scalar, that scalar has the void *
+my $ptr = ${($self->{codeExecAlloc} = Win32::API::Callback::HeapBlock->new(length($code)))};
+WriteMemory($ptr, $code, length($code));
+return $ptr;
+}
+
+
1;
__END__
@@ -161,17 +466,112 @@ Feedback is very appreciated.
=item *
Documentation is in the work. Either see the SYNOPSIS above
-or the samples in the F<samples> directory.
+or the samples in the F<samples> or the tests in the F<t> directory.
=back
+=head1 USAGE
+
+Win32::API::Callback uses a subset of the type letters of Win32::API. C Prototype
+interface isn't supported. Not all the type letters of Win32::API are supported
+in Win32::API::Callback.
+
+=over 4
+
+=item C<I>:
+value is an unsigned integer (unsigned int)
+
+=item C<i>:
+value is an signed integer (signed int or int)
+
+=item C<N>:
+value is a unsigned pointer sized number (unsigned long)
+
+=item C<n>:
+value is a signed pointer sized number (signed long or long)
+
+=item C<Q>:
+value is a unsigned 64 bit integer number (unsigned long long, unsigned __int64)
+See next item for details.
+
+=item C<q>:
+value is a signed 64 bit integer number (long long, __int64)
+If your perl has 'Q'/'q' quads support for L<pack> then Win32::API's 'q'
+is a normal perl numeric scalar. All 64 bit Perls have quad support. Almost no
+32 bit Perls have quad support. On 32 bit Perls, without quad support,
+Win32::API::Callback's 'q'/'Q' letter is a packed 8 byte string.
+So C<0x8000000050000000> from a perl with native Quad support
+would be written as C<"\x00\x00\x00\x50\x00\x00\x00\x80"> on a 32 bit
+Perl without Quad support. To improve the use of 64 bit integers with
+Win32::API::Callback on a 32 bit Perl without Quad support, there is
+a per Win32::API::Callback object setting called L<Win32::API/UseMI64>
+that causes all quads to be accepted as, and returned as L<Math::Int64>
+objects. 4 to 8 byte long pass by copy/return type C aggregate types
+are very rare in Windows, but they are supported as "in" and return
+types by using 'q'/'Q' on 32 and 64 bits. Converting between the C aggregate
+and its representation as a quad is up to the reader. For "out" in
+Win32::API::Callback (not "in"), if the argument is a reference, it will
+automatically be treated as a Math::Int64 object without having to
+previously call this function.
+
+=item C<F>:
+value is a floating point number (float)
+
+=item C<D>:
+value is a double precision number (double)
+
+=item C<Unimplemented types>:
+Unimplemented in Win32::API::Callback types such as shorts, chars, and
+smaller than "machine word size" (32/64bit) numbers can be processed
+by specifying N, then masking off the high bytes.
+For example, to get a char, specify N, then do C<$numeric_char = $_[2] & 0xFF;>
+in your Perl callback sub. To get a short, specify N, then do
+C<$numeric_char = $_[2] & 0xFFFF;> in your Perl callback sub.
+
+=back
+
+=head2 FUNCTIONS
+
+=head3 new
+
+ $CallbackObj = Win32::API::Callback->new( sub { print "hello world";},
+ 'NDF', 'Q', '__cdecl');
+ $CallbackObj = Win32::API::Callback->new( sub { print "hello world";},
+ $in, $out);
+
+Creates and returns a new Win32::API::Callback object. Calling convention
+parameter is optional. Calling convention parameter has same behaviour as
+Win32::API's calling convention parameter. C prototype parsing of Win32::API
+is not available with Win32::API::Callback. If the C caller assumes the
+callback has vararg parameters, and the platform is 64 bits/x64, in the first 4
+parameters, if they are floats or doubles they will be garbage. Note there is
+no way to create a Win32::API::Callback callback with a vararg prototype.
+A workaround is to put "enough" Ns as the in types, and stop looking at the @_
+slices in your Perl sub callback after a certain count. Usually the first
+parameter will somehow indicate how many additional stack parameters you are
+receiving. The Ns in @_ will eventually become garbage, technically they are
+the return address, saved registers, and C stack allocated variables of the
+caller. They are effectivly garbage for your vararg callback. All vararg
+callbacks on 32 bits must supply a calling convention, and it must be '__cdecl'
+or 'WINAPIV'.
+
+=head2 METHODS
+
+=head3 UseMI64
+
+See L<Win32::API/UseMI64>.
+
+=head1 SEE ALSO
+
+L<Win32::API::Callback::IATPatch>
+
=head1 AUTHOR
Aldo Calpini ( I<dada@perl.it> ).
+Daniel Dragan ( I<bulkdd@cpan.org> ).
=head1 MAINTAINER
Cosimo Streppone ( I<cosimo@cpan.org> ).
=cut
-
diff --git a/Master/tlpkg/tlperl/lib/Win32/API/Struct.pm b/Master/tlpkg/tlperl/lib/Win32/API/Struct.pm
index 3dda7d97e05..9a67ed7b6c4 100644
--- a/Master/tlpkg/tlperl/lib/Win32/API/Struct.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/API/Struct.pm
@@ -6,8 +6,10 @@
#
package Win32::API::Struct;
-
-$VERSION = '0.62';
+use strict;
+use warnings;
+use vars qw( $VERSION @ISA );
+$VERSION = '0.65';
use Carp;
use Win32::API::Type;
@@ -31,7 +33,7 @@ sub DEBUG {
sub typedef {
my $class = shift;
my $struct = shift;
- my ($type, $name);
+ my ($type, $name, @recog_arr);
my $self = {
align => undef,
typedef => [],
@@ -39,19 +41,51 @@ sub typedef {
while (defined($type = shift)) {
$name = shift;
$name =~ s/;$//;
- push(@{$self->{typedef}}, [recognize($type, $name)]);
+ @recog_arr = recognize($type, $name);
+#http://perlmonks.org/?node_id=978468, not catching the type not found here,
+#will lead to a div 0 later
+ if(@recog_arr != 3){
+ carp "Win32::API::Struct::typedef: unknown member type=\"$type\", name=\"$name\"";
+ return undef;
+ }
+ push(@{$self->{typedef}}, [@recog_arr]);
}
$Known{$struct} = $self;
+ $Win32::API::Type::Known{$struct} = '>';
return 1;
}
+#void ck_type($param, $proto, $param_num)
+sub ck_type {
+ my ($param, $proto) = @_;
+ #legacy LP prefix check
+ return if substr($proto, 0, 2) eq 'LP' && substr($proto, 2) eq $param;
+ #check if proto can be converted to base struct name
+ return if exists $Win32::API::Struct::Pointer{$proto} &&
+ $param eq $Win32::API::Struct::Pointer{$proto};
+ #check if proto can have * chopped off to convert to base struct name
+ $proto =~ s/\s*\*$//;
+ return if $proto eq $param;
+ croak("Win32::API::Call: supplied type (LP)\"".
+ $param."\"( *) doesn't match type \"".
+ $_[1]."\" for parameter ".
+ $_[2]." ");
+}
+
+#$basename = to_base_struct($pointername)
+sub to_base_struct {
+ return $Win32::API::Struct::Pointer{$_[0]}
+ if exists $Win32::API::Struct::Pointer{$_[0]};
+ die "Win32::API::Struct::Unpack unknown type";
+}
+
sub recognize {
my ($type, $name) = @_;
my ($size, $packing);
- if (is_known($type)) {
+ if (exists $Known{$type}) {
$packing = '>';
return ($name, $packing, $type);
}
@@ -69,12 +103,15 @@ sub recognize {
sub new {
my $class = shift;
- my ($type, $name);
+ my ($type, $name, $packing);
my $self = {typedef => [],};
if ($#_ == 0) {
if (is_known($_[0])) {
DEBUG "(PM)Struct::new: got '$_[0]'\n";
- $self->{typedef} = $Known{$_[0]}->{typedef};
+ if( ! defined ($self->{typedef} = $Known{$_[0]}->{typedef})){
+ carp 'Win32::API::Struct::new: unknown type="'.$_[0].'"';
+ return undef;
+ }
foreach my $member (@{$self->{typedef}}) {
($name, $packing, $type) = @$member;
next unless defined $name;
@@ -95,7 +132,7 @@ sub new {
# print "new: found member $name ($type)\n";
if (not exists $Win32::API::Type::Known{$type}) {
- warn "Unknown Win32::API::Struct type '$type'";
+ carp "Unknown Win32::API::Struct type '$type'";
return undef;
}
else {
@@ -197,17 +234,22 @@ sub getPack {
my ($type, $name, $type_size, $type_align);
my @items = ();
my @recipients = ();
+ my @buffer_ptrs = (); #this contains the struct_ptrs that were placed in the
+ #the struct, its part of "C func changes the struct ptr to a private allocated
+ #struct" code, it is push/poped only for struct ptrs, it is NOT a 1 to
+ #1 mapping between all struct members, so don't access it with indexes
my $align = $self->align();
foreach my $member (@{$self->{typedef}}) {
- ($name, $type, $orig) = @$member;
+ my ($name, $type, $orig) = @$member;
if ($type eq '>') {
- my ($subpacking, $subitems, $subrecipients, $subpacksize) =
+ my ($subpacking, $subitems, $subrecipients, $subpacksize, $subbuffersptrs) =
$self->{$name}->getPack();
DEBUG "(PM)Struct::getPack($self->{__typedef__}) ++ $subpacking\n";
push(@items, @$subitems);
push(@recipients, @$subrecipients);
+ push(@buffer_ptrs, @$subbuffersptrs);
$packing .= $subpacking;
$packed_size += $subpacksize;
}
@@ -221,9 +263,22 @@ sub getPack {
DEBUG "(PM)Struct::getPack($self->{__typedef__}) ++ $type\n";
if ($type eq 'p') {
- $type = ($Config{ptrsize} == 8) ? 'Q' : 'L';
+ $type = Win32::API::Type::pointer_pack_type();
push(@items, Win32::API::PointerTo($self->{$name}));
}
+ elsif ($type eq 'T') {
+ $type = Win32::API::Type::pointer_pack_type();
+ my $structptr;
+ if(ref($self->{$name})){
+ $self->{$name}->Pack();
+ $structptr = Win32::API::PointerTo($self->{$name}->{buffer});
+ }
+ else{
+ $structptr = 0;
+ }
+ push(@items, $structptr);
+ push(@buffer_ptrs, $structptr);
+ }
else {
push(@items, $self->{$name});
}
@@ -238,43 +293,59 @@ sub getPack {
DEBUG
"(PM)Struct::getPack: $self->{__typedef__}(buffer) = pack($packing, $packed_size)\n";
- return ($packing, [@items], [@recipients], $packed_size);
+ return ($packing, [@items], [@recipients], $packed_size, \@buffer_ptrs);
}
+# void $struct->Pack([$priv_warnings_flag]);
sub Pack {
my $self = shift;
- my ($packing, $items, $recipients) = $self->getPack();
+ my ($packing, $items);
+ ($packing, $items, $self->{buffer_recipients},
+ undef, $self->{buffer_ptrs}) = $self->getPack();
+ if(DEBUG){
DEBUG "(PM)Struct::Pack: $self->{__typedef__}(buffer) = pack($packing, @$items)\n";
-
- $self->{buffer} = pack($packing, @$items);
-
+ }
+
+ if($_[0]){ #Pack() on a new struct, without slice set, will cause lots of uninit
+ #warnings, sometimes its intentional to set up buffer recipients for a
+ #future UnPack()
+ no warnings 'uninitialized';
+ $self->{buffer} = pack($packing, @$items);
+ }
+ else{
+ $self->{buffer} = pack($packing, @$items);
+ }
if (DEBUG) {
for my $i (0 .. $self->sizeof - 1) {
printf "#pack# %3d: 0x%02x\n", $i, ord(substr($self->{buffer}, $i, 1));
}
}
-
- $self->{buffer_recipients} = $recipients;
}
sub getUnpack {
my $self = shift;
my $packing = "";
my $packed_size = 0;
- my ($type, $name, $type_size, $type_align);
- my @items = ();
+ my ($type, $name, $type_size, $type_align, $orig_type);
+ my (@items, @types, @type_names);
my $align = $self->align();
foreach my $member (@{$self->{typedef}}) {
- ($name, $type, $orig) = @$member;
+ my ($name, $type, $orig) = @$member;
if ($type eq '>') {
- my ($subpacking, $subpacksize, @subitems) = $self->{$name}->getUnpack();
+ my ($subpacking, $subpacksize, $subitems, $subtypes, $subtype_names) = $self->{$name}->getUnpack();
DEBUG "(PM)Struct::getUnpack($self->{__typedef__}) ++ $subpacking\n";
$packing .= $subpacking;
$packed_size += $subpacksize;
- push(@items, @subitems);
+ push(@items, @$subitems);
+ push(@types, @$subtypes);
+ push(@type_names, @$subtype_names);
}
else {
+ if($type eq 'T') {
+ $orig_type = $type;
+ $type = Win32::API::Type::pointer_pack_type();
+ }
my $repeat = 1;
if ($type =~ /\w\*(\d+)/) {
$repeat = $1;
@@ -285,30 +356,76 @@ sub getUnpack {
$type_align = (($packed_size + $type_size) % $type_size);
$packing .= "x" x $type_align . $type;
$packed_size += ( $type_size * $repeat ) + $type_align;
-
push(@items, $name);
+ if($orig_type){
+ push(@types, $orig_type);
+ undef($orig_type);
+ }
+ else{
+ push(@types, $type);
+ }
+ push(@type_names, $orig);
}
}
DEBUG "(PM)Struct::getUnpack($self->{__typedef__}): unpack($packing, @items)\n";
- return ($packing, $packed_size, @items);
+ return ($packing, $packed_size, \@items, \@types, \@type_names);
}
sub Unpack {
my $self = shift;
- my ($packing, undef, @items) = $self->getUnpack();
+ my ($packing, undef, $items, $types, $type_names) = $self->getUnpack();
my @itemvalue = unpack($packing, $self->{buffer});
DEBUG "(PM)Struct::Unpack: unpack($packing, buffer) = @itemvalue\n";
- foreach my $i (0 .. $#items) {
+ foreach my $i (0 .. $#$items) {
my $recipient = $self->{buffer_recipients}->[$i];
+ my $item = $$items[$i];
DEBUG "(PM)Struct::Unpack: %s(%s) = '%s' (0x%08x)\n",
$recipient->{__typedef__},
- $items[$i],
+ $item,
$itemvalue[$i],
$itemvalue[$i],
;
- $recipient->{$items[$i]} = $itemvalue[$i];
+ if($$types[$i] eq 'T'){
+my $oldstructptr = pop(@{$self->{buffer_ptrs}});
+my $newstructptr = $itemvalue[$i];
+my $SVMemberRef = \$recipient->{$item};
+
+if(!$newstructptr){ #new ptr is null
+ if($oldstructptr != $newstructptr){ #old ptr was true
+ carp "Win32::API::Struct::Unpack struct pointer".
+ " member \"".$item."\" was changed by C function,".
+ " possible resource leak";
+ }
+ $$SVMemberRef = undef;
+}
+else{ #new ptr is true
+ if($oldstructptr != $newstructptr){#old ptr was true, or null, but has changed, leak warning
+ carp "Win32::API::Struct::Unpack struct pointer".
+ " member \"".$item."\" was changed by C function,".
+ " possible resource leak";
+ }#create a ::Struct if the slice is undef, user had the slice set to undef
+
+ if (!ref($$SVMemberRef)){
+ $$SVMemberRef = Win32::API::Struct->new(to_base_struct($type_names->[$i]));
+ $$SVMemberRef->Pack(1); #buffer_recipients must be generated, no uninit warnings
+ }
+#must fix {buffer} with contents of the new struct, $structptr might be
+#null or might be a SVPV from a ::Struct that was ignored, in any case,
+#a foreign memory allocator is at work here
+ $$SVMemberRef->{buffer} = Win32::API::ReadMemory($newstructptr, $$SVMemberRef->sizeof)
+ if($oldstructptr != $newstructptr);
+#always must be called, if new ptr is not null, at this point, C func, did
+#one of 2 things, filled the old ::Struct's {buffer} PV, or gave a new struct *
+#from its own allocator, there is no way to tell if the struct contents changed
+#so Unpack() must be called
+ $$SVMemberRef->Unpack();
+}
+}
+ else{ #not a struct ptr
+ $recipient->{$item} = $itemvalue[$i];
- # DEBUG "(PM)Struct::Unpack: self.items[$i] = $self->{$items[$i]}\n";
+ # DEBUG "(PM)Struct::Unpack: self.items[$i] = $self->{$$items[$i]}\n";
+ }
}
}
@@ -329,7 +446,7 @@ sub Dump {
my $self = shift;
my $prefix = shift;
foreach my $member (@{$self->{typedef}}) {
- ($name, $packing, $type) = @$member;
+ my ($name, $packing, $type) = @$member;
if (ref($self->{$name})) {
$self->{$name}->Dump($name);
}
@@ -339,15 +456,22 @@ sub Dump {
}
}
-
+#the LP logic should be moved to parse_prototype, since only
+#::API::Call() ever understood the implied LP prefix, Struct::new never did
+#is_known then can be inlined away and sub deleted, it is not public API
sub is_known {
my $name = shift;
if (exists $Known{$name}) {
return 1;
}
else {
- if ($name =~ s/^LP//) {
- return exists $Known{$name};
+ my $nametest = $name;
+ if ($nametest =~ s/^LP//) {
+ return exists $Known{$nametest};
+ }
+ $nametest = $name;
+ if($nametest =~ s/\*$//){
+ return exists $Known{$nametest};
}
return 0;
}
@@ -440,7 +564,7 @@ Win32::API::Struct - C struct support package for Win32::API
This module enables you to define C structs for use with
Win32::API.
-See L<Win32::API> for more info about its usage.
+See L<Win32::API/USING STRUCTURES> for more info about its usage.
=head1 DESCRIPTION
@@ -457,7 +581,11 @@ of types and member names, just like in C. In fact, most of the
times you can cut the C definition for a structure and paste it
verbatim to your script, enclosing it in a C<qw()> block. The
function takes care of removing the semicolon after the member
-name.
+name. Win32::API::Struct does B<NOT> support Enums, Unions, or Bitfields.
+C<NAME> must not end in C<*>, typedef creates structs, not struct pointers.
+See L<Win32::API::Type/"typedef">
+on how to create a struct pointer type. Returns true on success, and undef on error.
+On error it L<warns|perlfunc/warn> with the specific reason.
The synopsis example could be written like this:
@@ -471,11 +599,14 @@ syntax), which is pretty cool:
LONG y;
};
-Also note that C<typedef> automatically defines an 'LPNAME' type,
-which holds a pointer to your structure. In the example above,
-'LPPOINT' is also defined and can be used in a call to a
-Win32::API (in fact, this is what you're really going to use when
-doing API calls).
+L<Win32::API/Call> automatically knows that an 'LPNAME' type, refers
+to a 'NAME' type struct. Also see L<Win32::API::Type/"typedef"> on how to declare
+pointers to struct types.
+
+Unlike in Win32::API, a single non-array char or CHAR struct member in a
+struct is numeric, NOT the first character of a string. UTF16 strings pointers
+will be garbage on read back (passing in works, returning doesn't) since
+the NULL character will often be the 2nd byte of the UTF16 string.
=item C<new NAME>
@@ -540,6 +671,38 @@ remember to backslash it, eg.
=back
+=head2 FOREIGN MEMORY ALLOCATORS
+
+Using Win32::API::Struct is not recommended in situations where a C function
+will return results to you by putting a pointer to a string or a pointer to
+another struct into your supplied struct. Win32::API::Struct will do its best
+to detect that a new pointer appeared and to read it contents into Perl, but
+that pointer will be tossed away after being read. If this pointer is
+something you must explicitly free, you have leaked it by using
+Win32::API::Struct to decode it. If this pointer is something you must pass back to
+the C API you are using, you lost/leaked it. If you pass NULL, or a ::Struct
+pointer in a ::Struct to C API, after the C API call, ::Struct will detect the
+pointer changed, it will read the new struct from the new pointer into
+Perl, and a new child ::Struct will appear in the hash slice
+of the parent ::Struct, if you pass this new child ::Struct into the C API
+it will be a B<COPY> of the struct the C API from Perl's allocation placed
+in the parent ::Struct. For C++-like APIs, this will be unacceptable and lead to
+crashes as the C Functions tries to free a memory block that didn't come from the
+allocator of the C Function. Windows has many memory allocators, each CRT
+(VS 2, 3, 4, 5, NT/6, 7.0, 7.1, 8, 9, 10) malloc, LocalAlloc, GlobalAlloc,
+HeapAlloc, (each version of C++ Runtime Library) "new", CoGetMalloc, CoTaskMemAlloc,
+NetApiBufferAllocate, VirtualAlloc, CryptMemAlloc, AllocADsMem, SHAlloc,
+SnmpUtilMemAlloc. None of these allocators' pointers are compatible with Perl's
+allocator. Some C APIs give you static global buffers which never are freed or freed
+automatically in the next call to a function from to that DLL.
+
+With foreign allocators, its best to treat to write a pointer class, bless the
+ref to scalar integer (holding the pointer) into that class to ensure that the
+DESTROY method will free the pointer and you never leak it, and your write
+method accessors using L<perlfunc/pack>, L<Win32::API/ReadMemory> and
+L<Win32::API/WriteMemory> around the pointer.
+
+
=head1 AUTHOR
Aldo Calpini ( I<dada@perl.it> ).
diff --git a/Master/tlpkg/tlperl/lib/Win32/API/Test.pm b/Master/tlpkg/tlperl/lib/Win32/API/Test.pm
index 55bf600b666..cd96b7c2b8d 100644
--- a/Master/tlpkg/tlperl/lib/Win32/API/Test.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/API/Test.pm
@@ -5,6 +5,8 @@
#
package Win32::API::Test;
+use strict;
+use warnings;
sub is_perl_64bit () {
use Config;
@@ -14,6 +16,16 @@ sub is_perl_64bit () {
return;
}
+sub can_fork () {
+ use Config;
+
+ my $native = $Config{d_fork} || $Config{d_pseudofork};
+ my $win32 = ($^O eq 'MSWin32' || $^O eq 'NetWare');
+ my $ithr = $Config{useithreads} and $Config{ccflags} =~ /-DPERL_IMPLICIT_SYS/;
+
+ return $native || ($win32 and $ithr);
+}
+
sub compiler_name () {
use Config;
my $cc = $Config{ccname};
@@ -73,7 +85,7 @@ sub compiler_version_from_shell () {
sub find_test_dll {
require File::Spec;
-
+ my $dll;
my $default_dll_name =
is_perl_64bit()
? 'API_test64.dll'
@@ -89,6 +101,18 @@ sub find_test_dll {
return (undef);
}
+#const optimize
+BEGIN {
+ package main;
+ use Config;
+ eval ' sub PTR_LET () { "'
+ .($Config{ptrsize} == 8 ? 'Q' : 'L').
+ '" }';
+ eval 'sub IV_LET () { '.($] <= 5.007002 ? 'L':'J').' }';
+ eval 'sub IV_SIZE () { '.length(pack(IV_LET(),0)).' }';
+ package Win32::API::Test;
+}
+
1;
__END__
diff --git a/Master/tlpkg/tlperl/lib/Win32/API/Type.pm b/Master/tlpkg/tlperl/lib/Win32/API/Type.pm
index 90e6d1ca0ad..0bdfb4fabf0 100644
--- a/Master/tlpkg/tlperl/lib/Win32/API/Type.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/API/Type.pm
@@ -12,17 +12,20 @@ package Win32::API::Type;
#
#######################################################################
-$VERSION = '0.62';
+use strict;
+use warnings;
+use vars qw( %Known %PackSize %Modifier %Pointer $VERSION @ISA );
+
+$VERSION = '0.69';
use Carp;
+BEGIN{
use Config;
-
+}
require Exporter; # to export the constants to the main:: space
require DynaLoader; # to dynuhlode the module.
@ISA = qw( Exporter DynaLoader );
-use vars qw( %Known %PackSize %Modifier %Pointer );
-
sub DEBUG {
if ($Win32::API::DEBUG) {
printf @_ if @_ or return 1;
@@ -32,6 +35,7 @@ sub DEBUG {
}
}
+sub pointer_pack_type ();
%Known = ();
%PackSize = ();
%Modifier = ();
@@ -102,10 +106,41 @@ sub new {
sub typedef {
my $class = shift;
my ($name, $type) = @_;
- my $packing = packing($type, $name);
+ $type =~ m/^\s*(.*?)\s*$/;
+ $type =~ m/^(.+?)\s*(\*)$/;
+ $type = $1;
+ $type .= $2 if defined $2;
+ $name =~ m/^\s*(.*?)\s*$/;
+ $name =~ m/^(.+?)\s*(\*)$/;
+ $name = $1;
+ $name .= $2 if defined $2;
+ #FIXME BUG, unsigned __int64 * doesn't pase in typedef, it does in parse_prototype
+ my $packing = packing($type, $name); #FIXME BUG
+ if(! defined $packing){
+ warn "Win32::API::Type::typedef: WARNING unknown type '$_[1]'";
+ return undef;
+ }
+ #Win32::API::Struct logic
+ #limitation, this won't alias a new struct type to an existing struct type
+ #this only creates new struct type pointer types to an existing struct type
+ if($packing eq '>'){
+ if(is_pointer($type)){
+ $packing = 'T';
+ $type =~ s/\s*\*$//; #chop off ' *'
+ $Win32::API::Struct::Pointer{$name} = $type;
+ }
+ else{
+ warn "Win32::API::Type::typedef: aliasing struct \"".$_[0]
+ ."\" to struct \"".$_[1]."\" not supported";
+ return undef;
+ }
+ }
DEBUG "(PM)Type::typedef: packing='$packing'\n";
- my $size = sizeof($type);
- $Known{$name} = $packing;
+ if($packing eq 'p'){
+ $Pointer{$name} = $Pointer{$type};
+ }else{
+ $Known{$name} = $packing;
+ }
return 1;
}
@@ -122,8 +157,11 @@ sub is_known {
}
}
-sub pointer_pack_type {
- return $Config{ptrsize} == 8 ? 'Q' : 'L';
+#const optimize
+BEGIN {
+ eval ' sub pointer_pack_type () { "'
+ .($Config{ptrsize} == 8 ? 'Q' : 'L').
+ '" }';
}
sub sizeof {
@@ -143,7 +181,7 @@ sub sizeof {
}
}
}
-
+# $packing_letter = packing( [$class = 'Win32::API::Type' ,] $type [, $pass_numeric])
sub packing {
# DEBUG "(PM)Type::packing: called by ". join("::", (caller(1))[0,3]). "\n";
@@ -156,7 +194,8 @@ sub packing {
}
my $type = ($self eq 'Win32::API::Type') ? shift : $self;
my $name = shift;
-
+ my $pass_numeric = shift;
+
# DEBUG "(PM)Type::packing: got '$type', '$name'\n";
my ($modifier, $size, $packing);
if (exists $Pointer{$type}) {
@@ -172,7 +211,7 @@ sub packing {
# DEBUG "(PM)packing: got modifier '$modifier', type '$type'\n";
}
- $type =~ s/\*$//;
+ $type =~ s/\s*\*$//; #kill whitespace "CHAR " isn't "CHAR"
if (exists $Known{$type}) {
if (defined $name and $name =~ s/\[(.*)\]$//) {
@@ -183,7 +222,7 @@ sub packing {
}
else {
$packing = $Known{$type};
- if ($is_pointer and $packing eq 'c') {
+ if ($is_pointer and ($packing eq 'c' or $packing eq 'S')) {
$packing = "p";
}
@@ -193,6 +232,9 @@ sub packing {
# DEBUG "(PM)Type::packing: applying modifier '$modifier' -> '$Modifier{$modifier}->{$type}'\n";
$packing = $Modifier{$modifier}->{$type};
+ if(!$pass_numeric) { #for older num unaware calls
+ substr($packing, 0, length("num"), '');
+ }
}
return $packing;
}
@@ -222,33 +264,59 @@ sub is_pointer {
}
sub Pack {
- my ($type, $arg) = @_;
+ my $type = $_[1];
my $pack_type = packing($type);
-
- if ($pack_type eq 'p') {
- $pack_type = 'Z*';
+ #print "Pack: type $type pack_type $pack_type\n";
+ if ($pack_type eq 'p') { #char or wide char pointer
+ #$pack_type = 'Z*';
+ return;
}
-
- $arg = pack($pack_type, $arg);
-
- return $arg;
+ elsif(IVSIZE() == 4 && ($pack_type eq 'q' || $pack_type eq 'Q')){
+ if($_[0]->UseMI64() || ref($_[2])){ #un/signed meaningless
+ $_[2] = Math::Int64::int64_to_native($_[2]);
+ }
+ else{
+ if(length($_[2]) < 8){
+ warn("Win32::API::Call value for 64 bit integer is under 8 bytes long");
+ $_[2] = pack('a8', $_[2]);
+ }
+ }
+ return;
+ }
+ $_[2] = pack($pack_type, $_[2]);
+ return;
}
sub Unpack {
- my ($type, $arg) = @_;
+ my $type = $_[1];
my $pack_type = packing($type);
if ($pack_type eq 'p') {
DEBUG "(PM)Type::Unpack: got packing 'p': is a pointer\n";
- $pack_type = 'Z*';
+ #$pack_type = 'Z*';
+ return;
}
-
- DEBUG "(PM)Type::Unpack: unpacking '$pack_type' '$arg'\n";
- $arg = unpack($pack_type, $arg);
- DEBUG "(PM)Type::Unpack: returning '" . ($arg || '') . "'\n";
- return $arg;
+ elsif(IVSIZE() == 4){
+ #todo debugging output
+ if($pack_type eq 'q'){
+ if($_[0]->UseMI64() || ref($_[2])){
+ $_[2] = Math::Int64::native_to_int64($_[2]);
+ DEBUG "(PM)Type::Unpack: returning signed Math::Int64 '".$_[2]."'\n";
+ }
+ return;
+ }elsif($pack_type eq 'Q'){
+ if($_[0]->UseMI64() || ref($_[2])){
+ $_[2] = Math::Int64::native_to_uint64($_[2]);
+ DEBUG "(PM)Type::Unpack: returning unsigned Math::Int64 '".$_[2]."'\n";
+ }
+ return;
+ }
+ }
+ DEBUG "(PM)Type::Unpack: unpacking '$pack_type' '$_[2]'\n";
+ $_[2] = unpack($pack_type, $_[2]);
+ DEBUG "(PM)Type::Unpack: returning '" . ($_[2] || '') . "'\n";
}
1;
@@ -288,6 +356,15 @@ This method defines a new type named C<NAME>. This actually just
creates an alias for the already-defined type C<TYPE>, which you
can use as a parameter in a Win32::API call.
+When C<TYPE> contains a Win32::API::Struct type declared with
+L<Win32::API::Struct/typedef> with " *" postfixed to C<TYPE> parameter,
+C<NAME> will be a alias for the pointer version of the struct type. Creating
+an alias for a struct type is not supported, you have to call
+L<Win32::API::Struct/typedef> again. Passing a struct type as C<TYPE>
+without the " *" postfix is not supported.
+
+L<Warns|perlfunc/warn> and returns undef if C<TYPE> is unknown, else returns true.
+
=item C<sizeof TYPE>
This returns the size, in bytes, of C<TYPE>. Acts just like
@@ -302,10 +379,42 @@ otherwise.
=head2 SUPPORTED TYPES
-This module should recognize all the types defined in the
-Win32 Platform SDK header files.
+This module recognizes many commonly used types defined in the Win32 Platform
+SDK header files, but not all. Types less than 13 years old are very unlikely
+to be the in built type database.
+
Please see the source for this module, in the C<__DATA__> section,
-for the full list.
+for the full list of builtin supported types.
+
+
+=head2 NOTES ON SELECT TYPES
+
+=over 4
+
+=item LPVOID
+
+Due to poor design, currently LPVOID is a char *, a string, not a number.
+It should really be a number. It is suggested to replace LPVOID in your
+C prototypes passed to Win32::API with UINT_PTR which is a pointer
+sized number.
+
+=item SOMETYPE **
+
+Currently ** types do not parse.
+
+=item void **
+
+Replace void ** in your C prototype that you pass to Win32::API::More with
+LPHANDLE.
+
+=item unsigned char
+
+=item signed char
+
+These 2 types by name force numeric handling. C<97> not C<"a">. C<UCHAR> is
+not a C<unsigned char> for numeric handling purposes.
+
+=back
=head1 AUTHOR
@@ -381,6 +490,7 @@ LONG64 q
LONGLONG q
LPARAM _P
LRESULT _P
+NTSTATUS l
REGSAM L
SC_HANDLE _P
SC_LOCK _P
@@ -410,7 +520,12 @@ long l
float f
double d
char c
+short s
+void c
+__int64 q
+#VOID is a 'c'? huh?
+#making void be a 'c' too, ~bulk88
#CRITICAL_SECTION 24 -- a structure
#LUID ? 8 -- a structure
#VOID 0
@@ -431,9 +546,12 @@ Q 8
s 2
S 2
p _P
+T _P
+t _P
[MODIFIER]
-unsigned int=I long=L short=S char=C
+unsigned int=numI long=numL short=numS char=numC
+signed int=numi long=numl short=nums char=numc
[POINTER]
INT_PTR INT
@@ -485,3 +603,4 @@ PVOID VOID
PWCHAR WCHAR
PWORD WORD
PWSTR WCHAR
+char* CHAR
diff --git a/Master/tlpkg/tlperl/lib/Win32/OLE.pm b/Master/tlpkg/tlperl/lib/Win32/OLE.pm
index a447f1aaa18..45158f6278f 100644
--- a/Master/tlpkg/tlperl/lib/Win32/OLE.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/OLE.pm
@@ -6,7 +6,7 @@ use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK @EXPORT_FAIL $AUTOLOAD
$CP $LCID $Warn $LastError $_NewEnum $_Unique);
-$VERSION = '0.1709';
+$VERSION = '0.1711';
use Carp;
use Exporter;
@@ -113,7 +113,7 @@ the local process has read access to the remote registry. The safest
=item Win32::OLE->EnumAllObjects([CALLBACK])
This class method returns the number Win32::OLE objects currently in
-existance. It will call the optional CALLBACK function for each of
+existence. It will call the optional CALLBACK function for each of
these objects:
$Count = Win32::OLE->EnumAllObjects(sub {
@@ -148,7 +148,7 @@ running instance of the specified OLE automation server. It returns
C<undef> if the server is not currently active. It will croak if
the class is not even registered. The optional DESTRUCTOR method takes
either a method name or a code reference. It is executed when the last
-reference to this object goes away. It is generally considered C<impolite>
+reference to this object goes away. It is generally considered rude
to stop applications that you did not start yourself.
=item Win32::OLE->GetObject(MONIKER[, DESTRUCTOR])
@@ -191,7 +191,7 @@ COINIT_MULTITHREADED model.
=item OBJECT->Invoke(METHOD[, ARGS])
The Invoke() object method is an alternate way to invoke OLE
-methods. It is normally equivalent to C<$OBJECT->METHOD(@ARGS)>. This
+methods. It is normally equivalent to C<$OBJECT-E<gt>METHOD(@ARGS)>. This
function must be used if the METHOD name contains characters not valid
in a Perl variable name (like foreign language characters). It can
also be used to invoke the default method of an object even if the
@@ -338,7 +338,7 @@ is resolved as
my $Sheet = $Worksheet->Item('Table1');
-provided that the $Worksheets object doesnot have a C<Table1> method
+provided that the $Worksheets object does not have a C<Table1> method
or property. This hack has been introduced to call the default method
of collections which did not name the method in their type library. The
recommended way to call the "unnamed" default method is:
@@ -391,7 +391,7 @@ function returned "Member not found" (0x80020003) you can write:
If COLLECTION is an OLE collection object then C<in $COLLECTION>
returns a list of all members of the collection. This is a shortcut
-for C<Win32::OLE::Enum->All($COLLECTION)>. It is most commonly used in
+for C<Win32::OLE::Enum-E<gt>All($COLLECTION)>. It is most commonly used in
a C<foreach> loop:
foreach my $value (in $collection) {
@@ -408,7 +408,7 @@ object (through the default method) and returns the value of the object.
my $ValOf = valof $Object;
$Object->{Value} = $NewValue;
-Now $ValOf still contains the old value wheras $RefOf would
+Now $ValOf still contains the old value whereas $RefOf would
resolve to the $NewValue because it is still a reference to
$Object.
@@ -419,7 +419,7 @@ objects to Perl values.
This function provides a concise way to set the values of multiple
properties of an object. It iterates over its arguments doing
-C<$OBJECT->{PROPERTYNAME} = $VALUE> on each trailing pair.
+C<$OBJECT-E<gt>{PROPERTYNAME} = $VALUE> on each trailing pair.
=back
@@ -515,7 +515,7 @@ would therefore not command the object to abort the closing action.
=head2 Module Options
The following module options can be accessed and modified with the
-C<Win32::OLE->Option> class method. In earlier versions of the Win32::OLE
+C<Win32::OLE-E<gt>Option> class method. In earlier versions of the Win32::OLE
module these options were manipulated directly as class variables. This
practice is now deprecated.
@@ -531,7 +531,7 @@ CP_UTF8. These constants are not exported by default.
=item LCID
-This variable controls the locale idnetifier used for all OLE calls.
+This variable controls the locale identifier used for all OLE calls.
It is set to LOCALE_NEUTRAL by default. Please check the
L<Win32::OLE::NLS> module for other locale related information.
@@ -560,7 +560,7 @@ an error happens. Valid values are:
3 Carp::croak
The error number and message (without Carp line/module info) are
-available through the C<Win32::OLE->LastError> class method.
+available through the C<Win32::OLE-E<gt>LastError> class method.
Alternatively the Warn option can be set to a CODE reference. E.g.
@@ -881,7 +881,7 @@ The package name has changed from "OLE" to "Win32::OLE".
=item 2
All functions of the form "Win32::OLEFoo" are now "Win32::OLE::Foo",
-though the old names are temporarily accomodated. Win32::OLECreateObject()
+though the old names are temporarily accommodated. Win32::OLECreateObject()
was changed to Win32::OLE::CreateObject(), and is now called
Win32::OLE::new() bowing to established convention for naming constructors.
The old names should be considered deprecated, and will be removed in the
@@ -963,6 +963,6 @@ related questions only, of course).
=head1 VERSION
-Version 0.1709 17 April 2008
+Version 0.1711 21 December 2013
=cut
diff --git a/Master/tlpkg/tlperl/lib/Win32/OLE/Const.pm b/Master/tlpkg/tlperl/lib/Win32/OLE/Const.pm
index 18456eebfe1..d0fe00b9ea7 100644
--- a/Master/tlpkg/tlperl/lib/Win32/OLE/Const.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/OLE/Const.pm
@@ -12,9 +12,9 @@ sub _Typelib {
# Filenames might have a resource index appended to it.
$filename = $1 if $filename =~ /^(.*\.(?:dll|exe))(\\\d+)$/i;
# Ignore if it looks like a file but doesn't exist.
- # We don't verify existance of monikers or filenames
+ # We don't verify existence of monikers or filenames
# without a full pathname.
- return unless -f $filename || $filename !~ /^\w:\\.*\.(exe|dll)$/;
+ return if $filename =~ /^\w:\\.*\.(exe|dll)$/ && !-f $filename;
push @$Typelibs, \@_;
}
unless (__PACKAGE__->_Typelibs("TypeLib")) {
@@ -157,7 +157,7 @@ constant definitions.
The parameters are the same as for the C<use> case.
-This method is generally preferrable when the typelib uses a non-english
+This method is generally preferable when the typelib uses a non-english
language and the constant names contain locale specific characters not
allowed in Perl variable names.
diff --git a/Master/tlpkg/tlperl/lib/Win32/OLE/NLS.pm b/Master/tlpkg/tlperl/lib/Win32/OLE/NLS.pm
index dc93f3b91c2..84ea0c77241 100644
--- a/Master/tlpkg/tlperl/lib/Win32/OLE/NLS.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/OLE/NLS.pm
@@ -591,7 +591,7 @@ subsystem seems to cache locale information.
=item MAKELANGID(LANG,SUBLANG)
-Creates a lnguage identifier from a primary language and a sublanguage.
+Creates a language identifier from a primary language and a sublanguage.
=item PRIMARYLANGID(LANGID)
diff --git a/Master/tlpkg/tlperl/lib/Win32/OLE/Variant.pm b/Master/tlpkg/tlperl/lib/Win32/OLE/Variant.pm
index 49e363da334..38fc6048209 100644
--- a/Master/tlpkg/tlperl/lib/Win32/OLE/Variant.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/OLE/Variant.pm
@@ -135,7 +135,7 @@ For VT_EMPTY and VT_NULL variants, the DATA argument may be omitted.
For all non-VT_ARRAY variants DATA specifies the initial value.
To create a SAFEARRAY variant, you have to specify the VT_ARRAY flag in
-addition to the variant base type of the array elemnts. In this cases
+addition to the variant base type of the array elements. In this cases
DATA must be a list specifying the dimensions of the array. Each element
can be either an element count (indices 0 to count-1) or an array
reference pointing to the lower and upper array bounds of this dimension:
@@ -145,7 +145,7 @@ reference pointing to the lower and upper array bounds of this dimension:
This creates a 2-dimensional SAFEARRAY of doubles with 4 elements:
(1,0), (1,1), (2,0) and (2,1).
-A special case is the the creation of one-dimensional VT_UI1 arrays with
+A special case is the creation of one-dimensional VT_UI1 arrays with
a string DATA argument:
my $String = Variant(VT_ARRAY|VT_UI1, "String");
@@ -200,7 +200,7 @@ C<$Int> is now a VT_I4 Variant object containing the value of element (1,2).
=item Currency([FORMAT[, LCID]])
-This method converts the VARIANT value into a formatted curency string. The
+This method converts the VARIANT value into a formatted currency string. The
FORMAT can be either an integer constant or a hash reference. Valid constants
are 0 and LOCALE_NOUSEROVERRIDE. You get the value of LOCALE_NOUSEROVERRIDE
from the Win32::OLE::NLS module:
@@ -253,7 +253,7 @@ The constants are available from the Win32::OLE::NLS module:
The following elements can be used to construct a date format string.
Characters must be specified exactly as given below (e.g. "dd" B<not> "DD").
-Spaces can be inserted anywhere between formating codes, other verbatim
+Spaces can be inserted anywhere between formatting codes, other verbatim
text should be included in single quotes.
d day of month
@@ -404,7 +404,7 @@ The constants are available from the Win32::OLE::NLS module:
The following elements can be used to construct a time format string.
Characters must be specified exactly as given below (e.g. "dd" B<not> "DD").
-Spaces can be inserted anywhere between formating codes, other verbatim
+Spaces can be inserted anywhere between formatting codes, other verbatim
text should be included in single quotes.
h hours; 12-hour clock
@@ -460,7 +460,7 @@ method first.
The Win32::OLE::Variant class used to have its own set of class variables
like C<$CP>, C<$LCID> and C<$Warn>. In version 0.1003 and later of the
-Win32::OLE module these variables have been eleminated. Now the settings
+Win32::OLE module these variables have been eliminated. Now the settings
of Win32::OLE are used by the Win32::OLE::Variant module too. Please read
the documentation of the C<Win32::OLE-&gt;Option> class method.
diff --git a/Master/tlpkg/tlperl/lib/Win32/Process/Info.pm b/Master/tlpkg/tlperl/lib/Win32/Process/Info.pm
index 45cfc373918..a9d9c8c91f5 100644
--- a/Master/tlpkg/tlperl/lib/Win32/Process/Info.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/Process/Info.pm
@@ -50,6 +50,10 @@ information is convenient (for the author!) about one or more Windows
32 processes. L</GetProcInfo> is therefore the most-important
method in the package. See it for more information.
+The process IDs made available are those returned by the variant in
+use. See the documentation to the individual variants for details,
+especially if you are a Cygwin user.
+
Unless explicitly stated otherwise, modules, variables, and so
on are considered private. That is, the author reserves the right
to make arbitrary changes in the way they work, without telling
@@ -70,7 +74,7 @@ use 5.006;
use strict;
use warnings;
-our $VERSION = '1.019';
+our $VERSION = '1.020';
use Carp;
use File::Spec;
@@ -101,6 +105,21 @@ our %static = (
my %variant_support;
BEGIN {
+ # Cygwin has its own idea of what a process ID is, independent of
+ # the underlying operating system. The Cygwin Perl implements this,
+ # so if we're Cygwin we need to compensate. This MUST return the
+ # Windows-native form under Cygwin, which means any variant which
+ # needs another form must override.
+
+ if ( $^O eq 'cygwin' ) {
+ *My_Pid = sub {
+ return Cygwin::pid_to_winpid( $$ );
+ };
+ } else {
+ *My_Pid = sub {
+ return $$;
+ };
+ }
%variant_support = (
NT => {
check_support => sub {
@@ -156,7 +175,9 @@ DLL_LOOP:
$wmi = Win32::OLE->GetObject(
'winmgmts:{impersonationLevel=impersonate,(Debug)}!//./root/cimv2'
);
- $wmi and $proc = $wmi->Get( "Win32_Process='$$'" );
+ $wmi and $proc = $wmi->Get(
+ sprintf q{Win32_Process='%s'}, __PACKAGE__->My_Pid()
+ );
};
Win32::OLE->Option( Warn => $old_warn );
$wmi or return 'Unable to get WMI object';
@@ -480,7 +501,7 @@ passing any necessary arguments.
my $idempotent;
- sub import {
+ sub import { ## no critic (RequireArgUnpacking)
my ($pkg, @params) = @_;
my (@args, @vars);
foreach (@params) {
@@ -490,8 +511,7 @@ passing any necessary arguments.
push @args, $_;
}
}
- # Note that if we ever become a subclass of Exporter
- # we will have to call __PACKAGE__->SUPER::import (@args);
+
if ($idempotent++) {
# Warning here maybe?
} else {
@@ -502,7 +522,12 @@ passing any necessary arguments.
$variant_support{$try}{check_support}->()} || $@;
}
}
+
return;
+
+# Do this if we become a subclass of Exporter
+# @_ = ( $pkg, @args );
+# goto &Exporter::import;;
}
# Return the number of times import() done.
@@ -631,6 +656,21 @@ sub SubProcInfo {
}
}
+=item $pid = $pi->My_Pid()
+
+This convenience method returns the process ID of the current process,
+in a form appropriate to the operating system and the variant in use.
+Normally, it simply returns C<$$>. But Cygwin has its own idea of what
+the process ID is, which may differ from Windows. Worse than that, under
+Cygwin the NT and WMI variants return Windows PIDs, while PT appears to
+return Cygwin PIDs.
+
+=cut
+
+# This is defined above, trickily, as an assignment to *My_Pid, so we
+# don't have to test $^O every time. It's above because code in a BEGIN
+# block needs it.
+
=item $text = Win32::Process::Info->variant_support_status($variant);
This static method returns the support status of the given variant. The
@@ -950,7 +990,7 @@ Thomas R. Wyant, III (F<wyant at cpan dot org>)
Copyright (C) 2001-2005 by E. I. DuPont de Nemours and Company, Inc. All
rights reserved.
-Copyright (C) 2007-2011 by Thomas R. Wyant, III
+Copyright (C) 2007-2011, 2013 by Thomas R. Wyant, III
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl 5.10.0. For more details, see the full text
diff --git a/Master/tlpkg/tlperl/lib/Win32/Process/Info/NT.pm b/Master/tlpkg/tlperl/lib/Win32/Process/Info/NT.pm
index 03f2469d337..26dd7ccba6e 100644
--- a/Master/tlpkg/tlperl/lib/Win32/Process/Info/NT.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/Process/Info/NT.pm
@@ -28,11 +28,13 @@ only be called via that package.
=head1 DESCRIPTION
-The main purpose of the Win32::Process::Info package is to get whatever
+The main purpose of the Win32::Process::Info::NT package is to get whatever
information is convenient (for the author!) about one or more Windows
32 processes. GetProcInfo (which see) is therefore the most-important
subroutine in the package. See it for more information.
+This package returns Windows process IDs, even under Cygwin.
+
Unless explicitly stated otherwise, modules, variables, and so
on are considered private. That is, the author reserves the right
to make arbitrary changes in the way they work, without telling
@@ -73,9 +75,9 @@ sub Win32::Process::Info::DummyRoutine::Call {
return undef; ## no critic (ProhibitExplicitReturnUndef)
}
-use base qw{Win32::Process::Info};
+use base qw{ Win32::Process::Info };
-our $VERSION = '1.019';
+our $VERSION = '1.020';
our $AdjustTokenPrivileges;
our $CloseHandle;
@@ -343,13 +345,14 @@ my $tac = TOKEN_READ;
my @pinf;
my $dat;
+my $my_pid = $self->My_Pid();
my %sid_to_name;
my @trydac = (
PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
PROCESS_QUERY_INFORMATION,
);
-foreach my $pid (map {$_ eq '.' ? $$ : $_} @args) {
+foreach my $pid (map {$_ eq '.' ? $my_pid : $_} @args) {
local $^E = 0;
$dat = $self->_build_hash (undef, ProcessId => $pid);
@@ -527,7 +530,10 @@ reference to the list is returned.
sub ListPids {
my ( $self, @args ) = @_;
my $filter = undef;
-@args and $filter = {map {(($_ eq '.' ? $$ : $_), 1)} @args};
+my $my_pid = $self->My_Pid();
+@args and $filter = {
+ map { ($_ eq '.' ? $my_pid : $_) => 1 } @args
+};
$EnumProcesses ||= _map ('PSAPI', 'EnumProcesses', [qw{P N P}], 'I');
my $psiz = 4;
my $bsiz = 0;
@@ -581,6 +587,12 @@ confess 'Programming error - should not get here';
# appropriate size. A further unpack may be necessary to extract
# data from the finally-obtained structure. You'll be seeing a
# lot of this pack/unpack idiom in the code that follows.
+#
+# Interestingly enough in February 2013 I found (fairly easily)
+# ConvertSidToStringSid(), which seems to do what I need, and
+# seems to have the same vintage as the other calls used above.
+# But in September of 2002 when I was writing this code I never
+# found it - certainly the docs cited never mentioned it.
sub _text_sid {
my $sid = shift;
@@ -599,7 +611,11 @@ $GetSidIdentifierAuthority ||=
_map ('ADVAPI32', 'GetSidIdentifierAuthority', [qw{P}], 'N');
my $sia = $GetSidIdentifierAuthority->Call ($sid);
$sia = pack 'L', $sia;
-$sia = unpack 'P6', $sia;
+# Occasionally we end up with an undef value here, which indicates a
+# failure. The docs say this only happens with an invalid SID, but what
+# do they know?
+defined( $sia = unpack 'P6', $sia )
+ or return;
# Get the number of subauthorities.
@@ -694,7 +710,7 @@ Thomas R. Wyant, III (F<wyant at cpan dot org>)
Copyright (C) 2001-2003 by E. I. DuPont de Nemours and Company, Inc.
-Copyright (C) 2007-2011 by Thomas R. Wyant, III
+Copyright (C) 2007-2011, 2013 by Thomas R. Wyant, III
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl 5.10.0. For more details, see the full text
diff --git a/Master/tlpkg/tlperl/lib/Win32/Process/Info/PT.pm b/Master/tlpkg/tlperl/lib/Win32/Process/Info/PT.pm
index 67bf7562cc9..17a9643dc05 100644
--- a/Master/tlpkg/tlperl/lib/Win32/Process/Info/PT.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/Process/Info/PT.pm
@@ -28,11 +28,15 @@ only be called via that package.
=head1 DESCRIPTION
-The main purpose of the Win32::Process::Info package is to get whatever
-information is convenient (for the author!) about one or more
+The main purpose of the Win32::Process::Info::PT package is to get
+whatever information is convenient (for the author!) about one or more
processes. GetProcInfo (which see) is therefore the most-important
method in the package. See it for more information.
+This package returns whatever process IDs are made available by
+Proc::ProcessTable. Under Cygwin, this seems to mean Cygwin process IDs,
+not Windows process IDs.
+
Unless explicitly stated otherwise, modules, variables, and so
on are considered private. That is, the author reserves the right
to make arbitrary changes in the way they work, without telling
@@ -63,8 +67,9 @@ package Win32::Process::Info::PT;
use strict;
use warnings;
-use base qw{Win32::Process::Info};
-our $VERSION = '1.019';
+use base qw{ Win32::Process::Info };
+
+our $VERSION = '1.020';
use Carp;
use File::Basename;
@@ -190,10 +195,15 @@ to be consistent with the other variants.
sub GetProcInfo {
my ($self, @args) = @_;
+
+ my $my_pid = $self->My_Pid();
my $opt = ref $args[0] eq 'HASH' ? shift @args : {};
my $tbl = Proc::ProcessTable->new ()->table ();
+
if (@args) {
- my %filter = map {(($_ eq '.' ? $$ : $_), 1)} @args;
+ my %filter = map {
+ ($_ eq '.' ? $my_pid : $_) => 1
+ } @args;
$tbl = [grep {$filter{$_->pid ()}} @$tbl];
}
my @pinf;
@@ -229,10 +239,15 @@ reference to the list is returned.
sub ListPids {
my ($self, @args) = @_;
+
my $tbl = Proc::ProcessTable->new ()->table ();
+ my $my_pid = $self->My_Pid();
my @pids;
+
if (@args) {
- my %filter = map {(($_ eq '.' ? $$ : $_), 1)} @args;
+ my %filter = map {
+ ($_ eq '.' ? $my_pid : $_) => 1
+ } @args;
@pids = grep {$filter{$_}} map {$_->pid} @$tbl;
} else {
@pids = map {$_->pid} @$tbl;
@@ -240,6 +255,10 @@ sub ListPids {
return wantarray ? @pids : \@pids;
}
+sub My_Pid {
+ return $$;
+}
+
=back
=head1 REQUIREMENTS
@@ -270,7 +289,7 @@ Thomas R. Wyant, III (F<wyant at cpan dot org>)
=head1 COPYRIGHT AND LICENSE
-Copyright (C) 2007, 2009-2011 by Thomas R. Wyant, III
+Copyright (C) 2007, 2009-2011, 2013 by Thomas R. Wyant, III
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl 5.10.0. For more details, see the full text
diff --git a/Master/tlpkg/tlperl/lib/Win32/Process/Info/WMI.pm b/Master/tlpkg/tlperl/lib/Win32/Process/Info/WMI.pm
index 06dcea9cfc4..ccebb6254f3 100644
--- a/Master/tlpkg/tlperl/lib/Win32/Process/Info/WMI.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/Process/Info/WMI.pm
@@ -24,6 +24,8 @@ only be called via that package.
This package implements the WMI-specific methods of
Win32::Process::Info.
+This package returns Windows process IDs, even under Cygwin.
+
The following methods should be considered public:
=over 4
@@ -35,8 +37,9 @@ package Win32::Process::Info::WMI;
use strict;
use warnings;
-use base qw{Win32::Process::Info};
-our $VERSION = '1.019';
+use base qw{ Win32::Process::Info };
+
+our $VERSION = '1.020';
use vars qw{%mutator};
use Carp;
@@ -208,9 +211,10 @@ be present.
sub _get_proc_objects {
my $self = shift;
+my $my_pid = $self->My_Pid();
my @procs = @_ ?
map {
- my $pi = $_ eq '.' ? $$ : $_;
+ my $pi = $_ eq '.' ? $my_pid : $_;
my $obj = $self->{wmi}->Get ("Win32_Process='$pi'");
Win32::OLE->LastError ? () : ($obj)
} @_ :
@@ -411,7 +415,7 @@ Thomas R. Wyant, III (F<wyant at cpan dot org>)
Copyright (C) 2001-2005 by E. I. DuPont de Nemours and Company, Inc.
-Copyright (C) 2007, 2010-2011 by Thomas R. Wyant, III
+Copyright (C) 2007, 2010-2011, 2013 by Thomas R. Wyant, III
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl 5.10.0. For more details, see the full text
diff --git a/Master/tlpkg/tlperl/lib/Win32/Shortcut.pm b/Master/tlpkg/tlperl/lib/Win32/Shortcut.pm
index 00200dead1f..f2846788282 100644
--- a/Master/tlpkg/tlperl/lib/Win32/Shortcut.pm
+++ b/Master/tlpkg/tlperl/lib/Win32/Shortcut.pm
@@ -8,7 +8,7 @@ package Win32::Shortcut;
#
#######################################################################
-$VERSION = "0.07";
+$VERSION = "0.08";
require Exporter;
require DynaLoader;
@@ -438,7 +438,7 @@ can be collapsed to:
Closes a shortcut object. Note that it is not "strictly" required to
close the objects you created, since the Win32::Shortcut objects are
-automatically closed when the program ends (or when you elsehow destroy
+automatically closed when the program ends (or when you somehow destroy
such an object).
Note also that a shortcut is not automatically saved when it is closed,
@@ -734,6 +734,8 @@ First implementation of the IShellLink interface (wow, it works!); can
Aldo Calpini L<dada@perl.it>
+Distributed under the terms of Larry Wall's Artistic License.
+
=head1 CREDITS
Thanks to: Jesse Dougherty, Dave Roth, ActiveWare, and the
@@ -744,9 +746,7 @@ Perl-Win32-Users community.
I<This program is FREE; you can redistribute, modify, disassemble, or
even reverse engineer this software at your will. Keep in mind,
however, that NOTHING IS GUARANTEED to work and everything you do is AT
-YOUR OWN RISK - I will not take responsability for any damage, loss of
+YOUR OWN RISK - I will not take responsibility for any damage, loss of
money and/or health that may arise from the use of this program!>
-This is distributed under the terms of Larry Wall's Artistic License.
-
=cut