-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathOLE.xs
6722 lines (5723 loc) · 167 KB
/
OLE.xs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* OLE.xs
*
* (c) 1995 Microsoft Corporation. All rights reserved.
* Developed by ActiveWare Internet Corp., now known as
* ActiveState Tool Corp., http://www.ActiveState.com
*
* Other modifications Copyright (c) 1997-1999 by Gurusamy Sarathy
* <[email protected]> and Jan Dubois <[email protected]>
*
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the README file.
*
*
* File contents:
*
* - C helper routines
* - Package Win32::OLE Constructor and method invocation
* - Package Win32::OLE::Tie Implements properties as tied hash
* - Package Win32::OLE::Const Load application constants from type library
* - Package Win32::OLE::Enum OLE collection enumeration
* - Package Win32::OLE::Variant Implements Perl VARIANT objects
* - Package Win32::OLE::NLS National Language Support
* - Package Win32::OLE::TypeLib Type library access
* - Package Win32::OLE::TypeInfo Type info access
*
*/
#ifdef __GNUC__
# pragma GCC diagnostic ignored "-Wwrite-strings"
#endif
// #define _DEBUG
#define register /* be gone */
#define MY_VERSION "Win32::OLE(" XS_VERSION ")"
#include <math.h> /* this hack gets around VC-5.0 brainmelt */
#define _WIN32_DCOM
#include <windows.h>
#include <ocidl.h>
#ifdef _DEBUG
# include <crtdbg.h>
# define DEBUGBREAK _CrtDbgBreak()
#else
# define DEBUGBREAK
#endif
// MingW is missing these 2 macros
#ifndef V_RECORD
# ifdef NONAMELESSUNION
# define V_RECORDINFO(X) ((X)->__VARIANT_NAME_1.__VARIANT_NAME_2.__VARIANT_NAME_3.__VARIANT_NAME_4.pRecInfo)
# define V_RECORD(X) ((X)->__VARIANT_NAME_1.__VARIANT_NAME_2.__VARIANT_NAME_3.__VARIANT_NAME_4.pvRecord)
# else
# define V_RECORDINFO(X) ((X)->pRecInfo)
# define V_RECORD(X) ((X)->pvRecord)
# endif
#endif
extern "C" {
#ifndef GUIDKIND_DEFAULT_SOURCE_DISP_IID
# define GUIDKIND_DEFAULT_SOURCE_DISP_IID 1
#endif
#ifdef __CYGWIN__
# undef WIN32 /* don't use with Cygwin & Perl */
# include <netdb.h>
# include <sys/socket.h>
# include <unistd.h>
# ifndef strrev
# define strrev my_strrev
static char *
my_strrev(char *str)
{
char *left = str;
char *right = left + strlen(left) - 1;
while (left < right) {
char temp = *left;
*left++ = *right;
*right-- = temp;
}
return str;
}
# endif /* strrev */
# ifndef stricmp
# define stricmp strcasecmp
# endif /* stricmp */
#endif
#define PERL_NO_GET_CONTEXT
#define NO_XSLOCKS
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include "patchlevel.h"
#undef WORD
typedef unsigned short WORD;
#ifndef _WIN64
# define DWORD_PTR DWORD
#endif
#if PERL_VERSION < 6
# error Win32::OLE requires Perl 5.6.0 or later
#endif
#ifdef USE_5005THREADS
# error Win32::OLE is incompatible with 5.005 style threads
#endif
#if PERL_VERSION > 6
# ifndef NO_MATHOMS
# define my_utf8_to_uv(s) utf8_to_uvuni(s, NULL)
# else
/* this has risk of buffer overflow but too complicated to fix */
# define my_utf8_to_uv(s) utf8_to_uvchr_buf(s, s+5, NULL)
# endif
#else
# if PERL_SUBVERSION > 0
# define my_utf8_to_uv(s) utf8_to_uv_simple(s, NULL)
# else
# define my_utf8_to_uv(s) utf8_to_uv(s, NULL)
# endif
#endif
#ifndef _DEBUG
# define DBG(a)
#else
# define DBG(a) MyDebug a
void
MyDebug(const char *pat, ...)
{
DWORD thread = GetCurrentThreadId();
void *context = PERL_GET_CONTEXT;
char szBuffer[512];
char *szMessage = szBuffer + sprintf(szBuffer, "[%d:%p] ", thread, context);
va_list args;
va_start(args, pat);
vsprintf(szMessage, pat, args);
OutputDebugString(szBuffer);
va_end(args);
}
#endif
/* constants */
static const DWORD WINOLE_MAGIC = 0x12344321;
static const DWORD WINOLEENUM_MAGIC = 0x12344322;
static const DWORD WINOLEVARIANT_MAGIC = 0x12344323;
static const DWORD WINOLETYPELIB_MAGIC = 0x12344324;
static const DWORD WINOLETYPEINFO_MAGIC = 0x12344325;
static const LCID lcidSystemDefault = 2 << 10;
/* static const LCID lcidDefault = 0; language neutral */
static const LCID lcidDefault = lcidSystemDefault;
static const UINT cpDefault = CP_ACP;
static const BOOL varDefault = FALSE;
static char PERL_OLE_ID[] = "___Perl___OleObject___";
static const int PERL_OLE_IDLEN = sizeof(PERL_OLE_ID)-1;
static const int OLE_BUF_SIZ = 256;
/* class names */
static char szUNICODESTRING[] = "Unicode::String";
static char szWINOLE[] = "Win32::OLE";
static char szWINOLEENUM[] = "Win32::OLE::Enum";
static char szWINOLEVARIANT[] = "Win32::OLE::Variant";
static char szWINOLETIE[] = "Win32::OLE::Tie";
static char szWINOLETYPELIB[] = "Win32::OLE::TypeLib";
static char szWINOLETYPEINFO[] = "Win32::OLE::TypeInfo";
/* class variable names */
static char LCID_NAME[] = "LCID";
static const int LCID_LEN = sizeof(LCID_NAME)-1;
static char CP_NAME[] = "CP";
static const int CP_LEN = sizeof(CP_NAME)-1;
static char VAR_NAME[] = "Variant";
static const int VAR_LEN = sizeof(VAR_NAME)-1;
static char WARN_NAME[] = "Warn";
static const int WARN_LEN = sizeof(WARN_NAME)-1;
static char _NEWENUM_NAME[] = "_NewEnum";
static const int _NEWENUM_LEN = sizeof(_NEWENUM_NAME)-1;
static char _UNIQUE_NAME[] = "_Unique";
static const int _UNIQUE_LEN = sizeof(_UNIQUE_NAME)-1;
static char LASTERR_NAME[] = "LastError";
static const int LASTERR_LEN = sizeof(LASTERR_NAME)-1;
static char TIE_NAME[] = "Tie";
static const int TIE_LEN = sizeof(TIE_NAME)-1;
#define COINIT_OLEINITIALIZE -1
#define COINIT_NO_INITIALIZE -2
typedef HRESULT (STDAPICALLTYPE FNCOINITIALIZEEX)(LPVOID, DWORD);
typedef void (STDAPICALLTYPE FNCOUNINITIALIZE)(void);
typedef HRESULT (STDAPICALLTYPE FNCOCREATEINSTANCEEX)
(REFCLSID, IUnknown*, DWORD, COSERVERINFO*, DWORD, MULTI_QI*);
typedef HWND (WINAPI FNHTMLHELP)(HWND hwndCaller, LPCSTR pszFile,
UINT uCommand, DWORD dwData);
typedef struct _tagOBJECTHEADER OBJECTHEADER;
/* per interpreter variables */
typedef struct
{
CRITICAL_SECTION CriticalSection;
OBJECTHEADER *pObj;
BOOL bInitialized;
HV *hv_unique;
/* DCOM function addresses are resolved dynamically */
HINSTANCE hOLE32;
FNCOINITIALIZEEX *pfnCoInitializeEx;
FNCOUNINITIALIZE *pfnCoUninitialize;
FNCOCREATEINSTANCEEX *pfnCoCreateInstanceEx;
/* HTML Help Control loaded dynamically */
HINSTANCE hHHCTRL;
FNHTMLHELP *pfnHtmlHelp;
} PERINTERP;
#ifdef PERL_IMPLICIT_CONTEXT
# define dPERINTERP \
SV **pinterp = hv_fetch(PL_modglobal, MY_VERSION, \
sizeof(MY_VERSION)-1, FALSE); \
if (!pinterp || !*pinterp || !SvIOK(*pinterp)) \
warn(MY_VERSION ": Per-interpreter data not initialized"); \
PERINTERP *pInterp = INT2PTR(PERINTERP*, SvIV(*pinterp))
# define INTERP pInterp
#else
static PERINTERP Interp;
# define dPERINTERP extern int errno
# define INTERP (&Interp)
#endif
#define g_pObj (INTERP->pObj)
#define g_bInitialized (INTERP->bInitialized)
#define g_CriticalSection (INTERP->CriticalSection)
#define g_hv_unique (INTERP->hv_unique)
#define g_hOLE32 (INTERP->hOLE32)
#define g_pfnCoInitializeEx (INTERP->pfnCoInitializeEx)
#define g_pfnCoUninitialize (INTERP->pfnCoUninitialize)
#define g_pfnCoCreateInstanceEx (INTERP->pfnCoCreateInstanceEx)
#define g_hHHCTRL (INTERP->hHHCTRL)
#define g_pfnHtmlHelp (INTERP->pfnHtmlHelp)
/* common object header */
typedef struct _tagOBJECTHEADER
{
long lMagic;
OBJECTHEADER *pNext;
OBJECTHEADER *pPrevious;
#ifdef PERL_IMPLICIT_CONTEXT
PERINTERP *pInterp;
#endif
} OBJECTHEADER;
#define OBJFLAG_DESTROYED 0x01
#define OBJFLAG_UNIQUE 0x02
/* Win32::OLE object */
class EventSink;
typedef struct
{
OBJECTHEADER header;
UV flags;
IDispatch *pDispatch;
ITypeInfo *pTypeInfo;
IEnumVARIANT *pEnum;
EventSink *pEventSink;
HV *self;
HV *hashTable;
SV *destroy;
unsigned short cFuncs;
unsigned short cVars;
unsigned int PropIndex;
} WINOLEOBJECT;
/* Win32::OLE::Enum object */
typedef struct
{
OBJECTHEADER header;
IEnumVARIANT *pEnum;
} WINOLEENUMOBJECT;
/* Win32::OLE::Variant object */
typedef struct
{
OBJECTHEADER header;
VARIANT variant;
VARIANT byref;
} WINOLEVARIANTOBJECT;
/* Win32::OLE::TypeLib object */
typedef struct
{
OBJECTHEADER header;
ITypeLib *pTypeLib;
TLIBATTR *pTLibAttr;
} WINOLETYPELIBOBJECT;
/* Win32::OLE::TypeInfo object */
typedef struct
{
OBJECTHEADER header;
ITypeInfo *pTypeInfo;
TYPEATTR *pTypeAttr;
} WINOLETYPEINFOOBJECT;
/* EventSink class */
class EventSink : public IDispatch
{
public:
// IUnknown methods
STDMETHOD(QueryInterface)(REFIID riid, LPVOID *ppvObj);
STDMETHOD_(ULONG, AddRef)(void);
STDMETHOD_(ULONG, Release)(void);
// IDispatch methods
STDMETHOD(GetTypeInfoCount)(UINT *pctinfo);
STDMETHOD(GetTypeInfo)(
UINT itinfo,
LCID lcid,
ITypeInfo **pptinfo);
STDMETHOD(GetIDsOfNames)(
REFIID riid,
OLECHAR **rgszNames,
UINT cNames,
LCID lcid,
DISPID *rgdispid);
STDMETHOD(Invoke)(
DISPID dispidMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS *pdispparams,
VARIANT *pvarResult,
EXCEPINFO *pexcepinfo,
UINT *puArgErr);
EventSink(pTHX_ WINOLEOBJECT *pObj, SV *events,
REFIID riid, ITypeInfo *pTypeInfo);
~EventSink(void);
HRESULT Advise(IConnectionPoint *pConnectionPoint);
void Unadvise(void);
private:
int m_refcount;
WINOLEOBJECT *m_pObj;
IConnectionPoint *m_pConnectionPoint;
DWORD m_dwCookie;
SV *m_events;
IID m_iid;
ITypeInfo *m_pTypeInfo;
#ifdef PERL_IMPLICIT_CONTEXT
pTHX;
#endif
};
/* Forwarder class */
class Forwarder : public IDispatch
{
public:
// IUnknown methods
STDMETHOD(QueryInterface)(REFIID riid, LPVOID *ppvObj);
STDMETHOD_(ULONG, AddRef)(void);
STDMETHOD_(ULONG, Release)(void);
// IDispatch methods
STDMETHOD(GetTypeInfoCount)(UINT *pctinfo);
STDMETHOD(GetTypeInfo)(
UINT itinfo,
LCID lcid,
ITypeInfo **pptinfo);
STDMETHOD(GetIDsOfNames)(
REFIID riid,
OLECHAR **rgszNames,
UINT cNames,
LCID lcid,
DISPID *rgdispid);
STDMETHOD(Invoke)(
DISPID dispidMember,
REFIID riid,
LCID lcid,
WORD wFlags,
DISPPARAMS *pdispparams,
VARIANT *pvarResult,
EXCEPINFO *pexcepinfo,
UINT *puArgErr);
Forwarder(pTHX_ HV *stash, SV *method);
~Forwarder(void);
private:
int m_refcount;
HV *m_stash;
SV *m_method;
#ifdef PERL_IMPLICIT_CONTEXT
pTHX;
#endif
};
/* forward declarations */
HRESULT SetSVFromVariantEx(pTHX_ VARIANTARG *pVariant, SV* sv, HV *stash,
BOOL bByRefObj=FALSE);
HRESULT SetVariantFromSVEx(pTHX_ SV* sv, VARIANT *pVariant, UINT cp,
LCID lcid);
HRESULT AssignVariantFromSV(pTHX_ SV* sv, VARIANT *pVariant,
UINT cp, LCID lcid);
//------------------------------------------------------------------------
void
MagicGet(pTHX_ SV *sv)
{
if (SvGMAGICAL(sv)) {
mg_get(sv);
// If the sv has lvalue magic (e.g. substr), it will stay magical
// and mg_get() will *not* set the public flags. We try to work
// around this here for at least the "substr" and "vec" cases.
//
// Setting the public POK flag should be safe because this function
// is only called on function arguments, which will be discarded
// once the function returns.
if (SvGMAGICAL(sv) && SvPOKp(sv))
SvPOK_on(sv);
}
}
inline void
SpinMessageLoop(void)
{
MSG msg;
DBG(("SpinMessageLoop\n"));
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
} /* SpinMessageLoop */
BOOL
IsLocalMachine(pTHX_ SV *host)
{
char szComputerName[MAX_COMPUTERNAME_LENGTH+1];
DWORD dwSize = sizeof(szComputerName);
char *pszMachine = SvPV_nolen(host);
char *pszName = pszMachine;
while (*pszName == '\\')
++pszName;
if (*pszName == '\0')
return TRUE;
/* Check against local computer name (from registry) */
if (GetComputerNameA(szComputerName, &dwSize)
&& stricmp(pszName, szComputerName) == 0)
{
return TRUE;
}
/* gethostname(), gethostbyname() and inet_addr() all call proxy functions
* in the Perl socket layer wrapper in win32sck.c. Therefore calling
* WSAStartup() here is not necessary.
*/
/* Determine main host name of local machine */
char szBuffer[200];
if (gethostname(szBuffer, sizeof(szBuffer)) != 0)
return FALSE;
/* Copy list of addresses for local machine */
struct hostent *pHostEnt = gethostbyname(szBuffer);
if (!pHostEnt)
return FALSE;
if (pHostEnt->h_addrtype != PF_INET || pHostEnt->h_length != 4) {
warn(MY_VERSION ": IsLocalMachine() gethostbyname failure");
return FALSE;
}
int index;
int count = 0;
char *pLocal;
while (pHostEnt->h_addr_list[count])
++count;
New(0, pLocal, 4*count, char);
for (index = 0; index < count; ++index)
memcpy(pLocal+4*index, pHostEnt->h_addr_list[index], 4);
/* Determine addresses of remote machine */
unsigned long ulRemoteAddr;
char *pRemote[2] = {NULL, NULL};
char **ppRemote = &pRemote[0];
if (isdigit(*pszMachine)) {
/* Convert numeric dotted address */
ulRemoteAddr = inet_addr(pszMachine);
if (ulRemoteAddr != INADDR_NONE)
pRemote[0] = (char*)&ulRemoteAddr;
}
else {
/* Lookup addresses for remote host name */
pHostEnt = gethostbyname(pszMachine);
if (pHostEnt)
if (pHostEnt->h_addrtype == PF_INET && pHostEnt->h_length == 4)
ppRemote = pHostEnt->h_addr_list;
}
/* Compare list of addresses of remote machine against local addresses */
while (*ppRemote) {
for (index = 0; index < count; ++index)
if (memcmp(pLocal+4*index, *ppRemote, 4) == 0) {
Safefree(pLocal);
return TRUE;
}
++ppRemote;
}
Safefree(pLocal);
return FALSE;
} /* IsLocalMachine */
HRESULT
CLSIDFromRemoteRegistry(pTHX_ SV *host, SV *progid, CLSID *pCLSID)
{
HKEY hKeyLocalMachine;
HKEY hKeyProgID;
LONG err;
HRESULT hr = S_OK;
err = RegConnectRegistryA(SvPV_nolen(host), HKEY_LOCAL_MACHINE, &hKeyLocalMachine);
if (err != ERROR_SUCCESS)
return HRESULT_FROM_WIN32(err);
SV *subkey = sv_2mortal(newSVpv("SOFTWARE\\Classes\\", 0));
sv_catsv(subkey, progid);
sv_catpv(subkey, "\\CLSID");
err = RegOpenKeyExA(hKeyLocalMachine, SvPV_nolen(subkey), 0, KEY_READ,
&hKeyProgID);
if (err != ERROR_SUCCESS)
hr = HRESULT_FROM_WIN32(err);
else {
DWORD dwType;
char szCLSID[100];
DWORD dwLength = sizeof(szCLSID);
err = RegQueryValueEx(hKeyProgID, "", NULL, &dwType,
(unsigned char*)&szCLSID, &dwLength);
if (err != ERROR_SUCCESS)
hr = HRESULT_FROM_WIN32(err);
else if (dwType == REG_SZ) {
OLECHAR wszCLSID[sizeof(szCLSID)];
MultiByteToWideChar(CP_ACP, 0, szCLSID, -1,
wszCLSID, sizeof(szCLSID));
hr = CLSIDFromString(wszCLSID, pCLSID);
}
else /* XXX maybe there is a more appropriate error code? */
hr = HRESULT_FROM_WIN32(ERROR_CANTREAD);
RegCloseKey(hKeyProgID);
}
RegCloseKey(hKeyLocalMachine);
return hr;
} /* CLSIDFromRemoteRegistry */
/* The following strategy is used to avoid the limitations of hardcoded
* buffer sizes: Conversion between wide char and multibyte strings
* is performed by GetMultiByte and GetWideChar respectively. The
* caller passes a default buffer and size. If the buffer is too small
* then the conversion routine allocates a new buffer that is big enough.
* The caller must free this buffer using the ReleaseBuffer function. */
inline void
ReleaseBuffer(pTHX_ void *pszHeap, void *pszStack)
{
if (pszHeap != pszStack && pszHeap)
Safefree(pszHeap);
}
char *
GetMultiByteEx(pTHX_ OLECHAR *wide, int *pcch, char *psz, int len, UINT cp)
{
int count;
if (psz) {
if (!wide || !*pcch) {
fail:
*psz = (char)0;
*pcch = 0;
return psz;
}
count = WideCharToMultiByte(cp, 0, wide, *pcch, psz, len, NULL, NULL);
if (count > 0)
goto succeed;
}
else if (!wide || !*pcch) {
Newz(0, psz, 1, char);
*pcch = 0;
return psz;
}
count = WideCharToMultiByte(cp, 0, wide, *pcch, NULL, 0, NULL, NULL);
if (count == 0) { /* should never happen */
warn(MY_VERSION ": GetMultiByte() failure: %lu", GetLastError());
DEBUGBREAK;
if (!psz)
New(0, psz, 1, char);
goto fail;
}
Newz(0, psz, count, char);
WideCharToMultiByte(cp, 0, wide, *pcch, psz, count, NULL, NULL);
succeed:
if (*pcch == -1)
*pcch = count - 1; /* because count includes the trailing '\0' */
else
*pcch = count;
return psz;
} /* GetMultiByteEx */
char *
GetMultiByte(pTHX_ OLECHAR *wide, char *psz, int len, UINT cp)
{
int cch = -1;
return GetMultiByteEx(aTHX_ wide, &cch, psz, len, cp);
}
SV *
sv_setbstr(pTHX_ SV *sv, BSTR bstr, UINT cp)
{
if (!bstr) {
if (sv)
sv_setpvn(sv, "", 0);
else
sv = newSVpvn("", 0);
return sv;
}
int len = WideCharToMultiByte(cp, 0, bstr, SysStringLen(bstr),
NULL, 0, NULL, NULL);
if (sv)
sv_grow(sv, len+1);
else
sv = newSV(len+1);
WideCharToMultiByte(cp, 0, bstr, SysStringLen(bstr),
SvPVX(sv), len, NULL, NULL);
SvPOK_on(sv);
SvPVX(sv)[len] = '\0';
SvCUR_set(sv, len);
if (cp == CP_UTF8) {
SvUTF8_on(sv);
sv_utf8_downgrade(sv, TRUE);
}
return sv;
}
OLECHAR *
GetWideChar(pTHX_ SV *sv, OLECHAR *wide, int len, UINT cp)
{
/* Note: len is number of OLECHARs, not bytes! */
int count;
STRLEN strlen;
char *str = NULL;
if (sv) {
str = SvPV(sv, strlen);
++strlen; // include trailing '\0' character
if (cp == CP_UTF8 && !SvUTF8(sv))
cp = CP_ACP;
}
if (wide) {
if (!str) {
*wide = (OLECHAR) 0;
return wide;
}
count = MultiByteToWideChar(cp, 0, str, (int)strlen, wide, len);
if (count > 0)
return wide;
}
else if (!str) {
Newz(0, wide, 1, OLECHAR);
return wide;
}
count = MultiByteToWideChar(cp, 0, str, (int)strlen, NULL, 0);
if (count == 0) {
warn(MY_VERSION ": GetWideChar() failure: %lu", GetLastError());
DEBUGBREAK;
if (!wide)
New(0, wide, 1, OLECHAR);
*wide = (OLECHAR) 0;
return wide;
}
Newz(0, wide, count, OLECHAR);
MultiByteToWideChar(cp, 0, str, (int)strlen, wide, count);
return wide;
} /* GetWideChar */
HV *
GetStash(pTHX_ SV *sv)
{
if (sv_isobject(sv))
return SvSTASH(SvRV(sv));
else if (SvPOK(sv))
return gv_stashsv(sv, TRUE);
else
return (HV*)&PL_sv_undef;
} /* GetStash */
HV *
GetWin32OleStash(pTHX_ SV *sv)
{
SV *pkg;
if (sv_isobject(sv))
pkg = newSVpv(HvNAME(SvSTASH(SvRV(sv))), 0);
else if (SvPOK(sv))
pkg = newSVpv(SvPVX(sv), SvCUR(sv));
else
pkg = newSVpv(szWINOLE, 0); /* should never happen */
char *pszColon = strrchr(SvPVX(pkg), ':');
if (pszColon) {
--pszColon;
while (pszColon > SvPVX(pkg) && *pszColon == ':')
--pszColon;
SvCUR_set(pkg, pszColon - SvPVX(pkg) + 1);
SvPVX(pkg)[SvCUR(pkg)] = '\0';
}
HV *stash = gv_stashsv(pkg, TRUE);
SvREFCNT_dec(pkg);
return stash;
} /* GetWin32OleStash */
IV
QueryPkgVar(pTHX_ HV *stash, char *var, STRLEN len, IV def=0)
{
SV *sv;
GV **gv = (GV**)hv_fetch(stash, var, (I32)len, FALSE);
if (gv && (sv = GvSV(*gv)) != NULL && SvIOK(sv)) {
DBG(("QueryPkgVar(%s::%s) returns %d\n", HvNAME(stash), var, SvIV(sv)));
return SvIV(sv);
}
DBG(("QueryPkgVar(%s::%s) default %d\n", HvNAME(stash), var, def));
return def;
}
void
SetLastOleError(pTHX_ HV *stash, HRESULT hr=S_OK, char *pszMsg=NULL)
{
/* Find $Win32::OLE::LastError */
SV *sv = sv_2mortal(newSVpv(HvNAME(stash), 0));
sv_catpvn(sv, "::", 2);
sv_catpvn(sv, LASTERR_NAME, LASTERR_LEN);
SV *lasterr = perl_get_sv(SvPV_nolen(sv), TRUE);
if (!lasterr) {
warn(MY_VERSION ": SetLastOleError: couldnot create variable %s",
LASTERR_NAME);
DEBUGBREAK;
return;
}
sv_setiv(lasterr, (IV)hr);
if (pszMsg) {
sv_setpv(lasterr, pszMsg);
SvIOK_on(lasterr);
}
}
void
ReportOleError(pTHX_ HV *stash, HRESULT hr, EXCEPINFO *pExcep=NULL,
SV *svAdd=NULL)
{
dSP;
SV *sv;
IV warnlvl = QueryPkgVar(aTHX_ stash, WARN_NAME, WARN_LEN);
GV **pgv = (GV**)hv_fetch(stash, WARN_NAME, WARN_LEN, FALSE);
CV *cv = Nullcv;
if (pgv && (sv = GvSV(*pgv)) && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV)
cv = (CV*)sv;
sv = sv_2mortal(newSV(200));
SvPOK_on(sv);
/* start with exception info */
if (pExcep && (pExcep->bstrSource || pExcep->bstrDescription)) {
char szSource[80] = "<Unknown Source>";
char szDesc[200] = "<No description provided>";
char *pszSource = szSource;
char *pszDesc = szDesc;
UINT cp = (UINT)QueryPkgVar(aTHX_ stash, CP_NAME, CP_LEN, cpDefault);
if (pExcep->bstrSource)
pszSource = GetMultiByte(aTHX_ pExcep->bstrSource,
szSource, sizeof(szSource), cp);
if (pExcep->bstrDescription)
pszDesc = GetMultiByte(aTHX_ pExcep->bstrDescription,
szDesc, sizeof(szDesc), cp);
sv_setpvf(sv, "OLE exception from \"%s\":\n\n%s\n\n",
pszSource, pszDesc);
ReleaseBuffer(aTHX_ pszSource, szSource);
ReleaseBuffer(aTHX_ pszDesc, szDesc);
/* SysFreeString accepts NULL too */
SysFreeString(pExcep->bstrSource);
SysFreeString(pExcep->bstrDescription);
SysFreeString(pExcep->bstrHelpFile);
}
/* always include OLE error code */
sv_catpvf(sv, MY_VERSION " error 0x%08x", hr);
/* try to append ': "error text"' from message catalog */
char *pszMsgText;
DWORD dwCount;
dwCount = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, hr, lcidSystemDefault,
(LPSTR)&pszMsgText, 0, NULL);
if (dwCount > 0) {
sv_catpv(sv, ": \"");
/* remove trailing dots and CRs/LFs from message */
while (dwCount > 0 &&
(pszMsgText[dwCount-1] < ' ' || pszMsgText[dwCount-1] == '.'))
pszMsgText[--dwCount] = '\0';
/* skip carriage returns in message text */
char *psz = pszMsgText;
char *pCR;
while ((pCR = strchr(psz, '\r')) != NULL) {
sv_catpvn(sv, psz, pCR-psz);
psz = pCR+1;
}
if (*psz != '\0')
sv_catpv(sv, psz);
sv_catpv(sv, "\"");
LocalFree(pszMsgText);
}
/* add additional error details */
if (svAdd) {
sv_catpv(sv, "\n ");
sv_catsv(sv, svAdd);
}
/* try to keep linelength of description below 80 chars. */
char *pLastBlank = NULL;
char *pch = SvPVX(sv);
int cch;
for (cch = 0; *pch; ++pch, ++cch) {
if (*pch == ' ') {
pLastBlank = pch;
}
else if (*pch == '\n') {
pLastBlank = pch;
cch = 0;
}
if (cch > 76 && pLastBlank) {
*pLastBlank = '\n';
cch = (int)(pch - pLastBlank);
}
}
SetLastOleError(aTHX_ stash, hr, SvPVX(sv));
DBG(("ReportOleError: hr=0x%08x warnlvl=%d\n%s", hr, warnlvl, SvPVX(sv)));
if (!cv && (warnlvl > 1 || (warnlvl == 1 && (PL_dowarn & G_WARN_ON)))) {
if (warnlvl < 3) {
cv = perl_get_cv("Carp::carp", FALSE);
if (!cv)
warn("%s", SvPVX(sv));
}
else {
cv = perl_get_cv("Carp::croak", FALSE);
if (!cv)
croak("%s", SvPVX(sv));
}
}
if (cv) {
ENTER;
SAVETMPS;
PUSHMARK(sp);
XPUSHs(sv);
PUTBACK;
perl_call_sv((SV*)cv, G_DISCARD|G_EVAL);
FREETMPS;
LEAVE;
if (SvTRUE(ERRSV)) {
#if defined(ACTIVEPERL_CHANGELIST) || (PERL_VERSION > 6 || PERL_SUBVERSION > 0)
if (sv_isobject(ERRSV))
croak(Nullch); /* rethrow exception */
else
croak("%s", SvPV_nolen(ERRSV));
#else
croak("%s", SvPV_nolen(ERRSV));
#endif
}
}
} /* ReportOleError */
inline BOOL
CheckOleError(pTHX_ HV *stash, HRESULT hr, EXCEPINFO *pExcep=NULL,
SV *svAdd=NULL)
{
if (FAILED(hr)) {
ReportOleError(aTHX_ stash, hr, pExcep, svAdd);
return TRUE;
}
return FALSE;
}
SV *
CheckDestroyFunction(pTHX_ SV *sv, char *szMethod)
{
/* undef */
if (!SvOK(sv))
return NULL;
/* method name or CODE ref */
if (SvPOK(sv) || (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV))
return sv;
warn("%s(): DESTROY must be a method name or a CODE reference", szMethod);
DEBUGBREAK;
return NULL;
}
void
AddToObjectChain(pTHX_ OBJECTHEADER *pHeader, long lMagic)
{
dPERINTERP;
DBG(("AddToObjectChain(0x%08x) lMagic=0x%08x", pHeader, lMagic));
EnterCriticalSection(&g_CriticalSection);
pHeader->lMagic = lMagic;
pHeader->pPrevious = NULL;
pHeader->pNext = g_pObj;
#ifdef PERL_IMPLICIT_CONTEXT
pHeader->pInterp = INTERP;
#endif
if (g_pObj)
g_pObj->pPrevious = pHeader;
g_pObj = pHeader;
LeaveCriticalSection(&g_CriticalSection);