-
Notifications
You must be signed in to change notification settings - Fork 8
/
Tcl.xs
1926 lines (1716 loc) · 46.1 KB
/
Tcl.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
/*
* Tcl.xs --
*
* This file contains XS code for the Perl's Tcl bridge module.
*
* Copyright (c) 1994-1997, Malcolm Beattie
* Copyright (c) 2003-2024, Vadim Konovalov
* Copyright (c) 2004 ActiveState Corp., a division of Sophos PLC
*
*/
#define PERL_NO_GET_CONTEXT /* we want efficiency */
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#ifndef DEBUG_REFCOUNTS
#define DEBUG_REFCOUNTS 0
#endif
#include <tcl.h>
#ifdef USE_TCL_STUBS
/* Let Tcl_Init() stub could be pointed by a function pointer.
* Since tcl8.5, Tcl_Init() is defined as a macro with an argument and
* unable to be assigned to a function pointer. We need to redefine it back
* to tcl8.4 style .
*/
#ifdef Tcl_Init
# undef Tcl_Init
# define Tcl_Init (tclStubsPtr->tcl_Init)
#endif
/*
* If we use the Tcl stubs mechanism, this provides us Tcl version
* and direct dll independence, but we must force the loading of
* the dll ourselves based on a set of heuristics in NpLoadLibrary.
*/
#ifndef TCL_LIB_FILE
# ifdef WIN32
# define TCL_LIB_FILE "tcl84.dll"
# elif defined(__APPLE__)
# define TCL_LIB_FILE "Tcl"
# elif defined(__hpux)
# define TCL_LIB_FILE "libtcl8.4.sl"
# else
# define TCL_LIB_FILE "libtcl8.4.so"
# endif
#endif
/*
* Default directory in which to look for Tcl/Tk libraries. The
* symbol is defined by Makefile.
*/
#ifndef LIB_RUNTIME_DIR
# define LIB_RUNTIME_DIR "."
#endif
static char defaultLibraryDir[sizeof(LIB_RUNTIME_DIR)+200] = LIB_RUNTIME_DIR;
#if defined(WIN32)
#ifndef HMODULE
#define HMODULE void *
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#define dlopen(libname, flags) LoadLibrary(libname)
#define dlclose(path) FreeLibrary((HMODULE) path)
#define DLSYM(handle, symbol, type, proc) \
(proc = (type) GetProcAddress((HINSTANCE) handle, symbol))
#define snprintf _snprintf
#elif defined(__APPLE__)
#ifdef SEE_TICKET_125664 /*sorry, no replacement for deprecated function */
#include <CoreServices/CoreServices.h>
static short DOMAINS[] = {
kUserDomain,
kLocalDomain,
kNetworkDomain,
kSystemDomain
};
static const int DOMAINS_LEN = sizeof(DOMAINS)/sizeof(DOMAINS[0]);
#endif
#elif defined(__hpux)
/* HPUX requires shl_* routines */
#include <dl.h>
#define HMODULE shl_t
#define dlopen(libname, flags) shl_load(libname, \
BIND_DEFERRED|BIND_VERBOSE|DYNAMIC_PATH, 0L)
#define dlclose(path) shl_unload((shl_t) path)
#define DLSYM(handle, symbol, type, proc) \
if (shl_findsym(&handle, symbol, (short) TYPE_PROCEDURE, \
(void *) &proc) != 0) { proc = NULL; }
#endif
#ifndef HMODULE
#include <dlfcn.h>
#define HMODULE void *
#define DLSYM(handle, symbol, type, proc) \
(proc = (type) dlsym(handle, symbol))
#endif
#ifndef MAX_PATH
#define MAX_PATH 1024
#endif
/*
* Tcl library handle
*/
static HMODULE tclHandle = NULL;
static Tcl_Interp *g_Interp = NULL;
static int (* tclKit_AppInit)(Tcl_Interp *) = NULL;
#else
/*
* !USE_TCL_STUBS
*/
static int (* tclKit_AppInit)(Tcl_Interp *) = Tcl_Init;
#if defined(HAVE_TKINIT) && defined(WIN32)
HANDLE _hinst = 0;
BOOL APIENTRY
DllMain(HINSTANCE hInst, DWORD reason, LPVOID reserved) {
_hinst = hInst;
return TRUE;
}
#endif
#endif
typedef Tcl_Interp *Tcl;
typedef AV *Tcl__Var;
#ifdef HAVE_TKINIT
EXTERN char * TclSetPreInitScript (char * string);
void TclpInitLibraryPath(char **valuePtr, int *lengthPtr, Tcl_Encoding *encodingPtr);
EXTERN void TkWinSetHINSTANCE (HINSTANCE hInstance);
#endif
#ifdef HAVE_BLTINIT
extern Tcl_PackageInitProc Blt_Init, Blt_SafeInit;
#endif
/*
* Variables denoting the Tcl object types defined in the core.
* These may not exist - guard against NULL result.
*/
static const Tcl_ObjType *tclBooleanTypePtr = NULL;
static const Tcl_ObjType *tclByteArrayTypePtr = NULL;
static const Tcl_ObjType *tclDoubleTypePtr = NULL;
static const Tcl_ObjType *tclIntTypePtr = NULL;
static const Tcl_ObjType *tclListTypePtr = NULL;
static const Tcl_ObjType *tclStringTypePtr = NULL;
static const Tcl_ObjType *tclWideIntTypePtr = NULL;
/*
* This tells us whether Tcl is in a "callable" state. Set to 1 in BOOT
* and 0 in Tcl__Finalize (END). Once finalized, we should not make any
* more calls to Tcl_* APIs.
* hvInterps is a hash that records all live interps, so that we can
* force their deletion before the finalization.
*/
static int initialized = 0;
static HV *hvInterps = NULL;
/*
* FUNCTIONS
*/
#ifdef USE_TCL_STUBS
/*
*----------------------------------------------------------------------
*
* NpLoadLibrary --
*
*
* Results:
* Stores the handle of the library found in tclHandle and the
* name it successfully loaded from in dllFilename (if dllFilenameSize
is != 0).
*
* Side effects:
* Loads the library - user needs to dlclose it..
*
*----------------------------------------------------------------------
*/
static int
NpLoadLibrary(pTHX_ HMODULE *tclHandle, char *dllFilename, int dllFilenameSize)
{
char *dl_path, libname[MAX_PATH];
HMODULE handle = (HMODULE) NULL;
char buffer[1024]; buffer[0]=0; /* DELETE this after things are settled TODO */
/*
* Try a user-supplied Tcl dll to start with.
* If the var is supplied, force this to be correct or error out.
*/
dl_path = SvPV_nolen(get_sv("Tcl::DL_PATH", TRUE));
if (dl_path && *dl_path) {
handle = dlopen(dl_path, RTLD_NOW | RTLD_GLOBAL);
if (handle) {
memcpy(libname, dl_path, MAX_PATH);
} else {
#if !defined(WIN32) && !defined(__hpux)
char *error = dlerror();
if (error != NULL) {
warn("%s",error);
}
#endif
warn("NpLoadLibrary: could not find Tcl library at '%s'", dl_path);
return TCL_ERROR;
}
}
#ifdef __APPLE__
#ifdef SEE_TICKET_125664 /*sorry, no replacement for deprecated function */
if (!handle) {
OSErr oserr;
FSRef ref;
int i;
for (i = 0; i < DOMAINS_LEN; i++) {
oserr = FSFindFolder(DOMAINS[i], kFrameworksFolderType,
kDontCreateFolder, &ref);
if (oserr != noErr) {
continue;
}
oserr = FSRefMakePath(&ref, (UInt8*)libname, sizeof(libname));
if (oserr != noErr) {
continue;
}
/*
* This should really just try loading Tcl.framework/Tcl, but will
* fail if the user has requested an alternate TCL_LIB_FILE.
*/
strcat(libname, "/Tcl.framework/" TCL_LIB_FILE);
handle = dlopen(libname, RTLD_NOW | RTLD_GLOBAL);
sprintf(buffer,"%sfailed dlopen(%s,...);\n", buffer, libname);
if (handle) {
break;
}
}
}
#endif
#endif
if (!handle) {
if (strlen(TCL_LIB_FILE) < 3) {
warn("Invalid base Tcl library filename provided: '%s'", TCL_LIB_FILE);
return TCL_ERROR;
}
if (!handle) {
/* Try based on full path. */
snprintf(libname, MAX_PATH-1, "%s/%s", defaultLibraryDir, TCL_LIB_FILE);
sprintf(buffer,"%sfailed dlopen(%s,...);\n", buffer, libname);
handle = dlopen(libname, RTLD_NOW | RTLD_GLOBAL);
}
if (!handle) {
/* Try based on anywhere in the path. */
strcpy(libname, TCL_LIB_FILE);
sprintf(buffer,"%sfailed dlopen(%s,...);\n", buffer, libname);
handle = dlopen(libname, RTLD_NOW | RTLD_GLOBAL);
}
if (!handle) {
/* Try different versions anywhere in the path. */
sprintf(buffer,"%sfailed dlopen(%s,...);\n", buffer, libname);
char *pos = strstr(libname, "tcl8")+4;
if (*pos == '.') {
pos++;
}
*pos = '7'; /* count down from '7' to '0': 8.7, 8.6, 8.5, 8.4, ... */
do {
sprintf(buffer,"%strying dlopen(%s,...)\n", buffer, libname);
handle = dlopen(libname, RTLD_NOW | RTLD_GLOBAL);
} while (!handle && (--*pos >= '0'));
if (!handle) {
warn("%sfailed all posible tcl vers 8.x from 9 down to 0", buffer);
return TCL_ERROR;
}
}
}
#ifdef WIN32
if (!handle) {
char path[MAX_PATH], vers[MAX_PATH];
DWORD result, size = MAX_PATH;
HKEY regKey;
#define TCL_REG_DIR_KEY "Software\\ActiveState\\ActiveTcl"
result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TCL_REG_DIR_KEY, 0,
KEY_READ, ®Key);
if (result != ERROR_SUCCESS) {
warn("Could not access registry \"HKLM\\%s\"\n", TCL_REG_DIR_KEY);
result = RegOpenKeyEx(HKEY_CURRENT_USER, TCL_REG_DIR_KEY, 0,
KEY_READ, ®Key);
if (result != ERROR_SUCCESS) {
warn("Could not access registry \"HKCU\\%s\"\n",
TCL_REG_DIR_KEY);
return TCL_ERROR;
}
}
result = RegQueryValueEx(regKey, "CurrentVersion", NULL, NULL,
vers, &size);
RegCloseKey(regKey);
if (result != ERROR_SUCCESS) {
warn("Could not access registry \"%s\" CurrentVersion\n",
TCL_REG_DIR_KEY);
return TCL_ERROR;
}
snprintf(path, MAX_PATH-1, "%s\\%s", TCL_REG_DIR_KEY, vers);
result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, path, 0, KEY_READ, ®Key);
if (result != ERROR_SUCCESS) {
warn("Could not access registry \"%s\"\n", path);
return TCL_ERROR;
}
size = MAX_PATH;
result = RegQueryValueEx(regKey, NULL, NULL, NULL, path, &size);
RegCloseKey(regKey);
if (result != ERROR_SUCCESS) {
warn("Could not access registry \"%s\" Default\n", TCL_REG_DIR_KEY);
return TCL_ERROR;
}
warn("Found current Tcl installation at \"%s\"\n", path);
snprintf(libname, MAX_PATH-1, "%s\\bin\\%s", path, TCL_LIB_FILE);
handle = dlopen(libname, RTLD_NOW | RTLD_GLOBAL);
}
#endif
if (!handle) {
warn("NpLoadLibrary: could not find Tcl dll\n");
return TCL_ERROR;
}
*tclHandle = handle;
if (dllFilenameSize > 0) {
memcpy(dllFilename, libname, dllFilenameSize);
}
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* NpInitialize --
*
* Create the main interpreter.
*
* Results:
* TCL_OK or TCL_ERROR - whether succeeded or not
*
* Side effects:
* Will panic if called twice. (Must call DestroyMainInterp in between)
*
*----------------------------------------------------------------------
*/
static int
NpInitialize(pTHX_ SV *X)
{
static Tcl_Interp * (* createInterp)() = NULL;
static void (* findExecutable)(char *) = NULL;
/*
* We want the Tcl_InitStubs func static to ourselves - before Tcl
* is loaded dynamically and possibly changes it.
* Variable initstubs have to be declared as volatile to prevent
* compiler optimizing it out.
*/
static const char *(*volatile initstubs)(Tcl_Interp *, const char *, int)
= Tcl_InitStubs;
char dllFilename[MAX_PATH];
dllFilename[0] = '\0';
#ifdef USE_TCL_STUBS
/*
* Determine the libname and version number dynamically
*/
if (tclHandle == NULL) {
/*
* First see if some other part didn't already load Tcl.
*/
DLSYM(tclHandle, "Tcl_CreateInterp", Tcl_Interp * (*)(), createInterp);
if (createInterp == NULL) {
if (NpLoadLibrary(aTHX_ &tclHandle, dllFilename, MAX_PATH)
!= TCL_OK) {
warn("Failed to load Tcl dll!");
return TCL_ERROR;
}
}
DLSYM(tclHandle, "Tcl_CreateInterp", Tcl_Interp * (*)(), createInterp);
if (createInterp == NULL) {
#if !defined(WIN32) && !defined(__hpux)
char *error = dlerror();
if (error != NULL) {
warn("%s",error);
}
#endif
return TCL_ERROR;
}
DLSYM(tclHandle, "Tcl_FindExecutable", void (*)(char *),
findExecutable);
DLSYM(tclHandle, "TclKit_AppInit", int (*)(Tcl_Interp *),
tclKit_AppInit);
}
#else
createInterp = Tcl_CreateInterp;
findExecutable = Tcl_FindExecutable;
#endif
#ifdef WIN32
if (dllFilename[0] == '\0') {
GetModuleFileNameA((HINSTANCE) tclHandle, dllFilename, MAX_PATH);
}
findExecutable(dllFilename);
#else
findExecutable(X && SvPOK(X) ? SvPV_nolen(X) : NULL);
#endif
g_Interp = createInterp();
if (g_Interp == (Tcl_Interp *) NULL) {
warn("Failed to create main Tcl interpreter!");
return TCL_ERROR;
}
/*
* Until Tcl_InitStubs is called, we cannot make any Tcl/Tk API
* calls without grabbing them by symbol out of the dll.
* This will be Tcl_PkgRequire for non-stubs builds.
*/
if (initstubs(g_Interp, "8.4", 0) == NULL) {
warn("Failed to initialize Tcl stubs!");
return TCL_ERROR;
}
/*
* If we didn't find TclKit_AppInit, then this is a regular Tcl
* installation, so invoke Tcl_Init.
* Otherwise, we need to set the kit path to indicate we want to
* use the dll as our base kit.
*/
if (tclKit_AppInit == NULL) {
tclKit_AppInit = Tcl_Init;
} else {
char * (* tclKit_SetKitPath)(char *) = NULL;
/*
* We need to see if this has TclKit_SetKitPath. This is in
* special base kit dlls that have embedded data in the dll.
*/
if (dllFilename[0] != '\0') {
DLSYM(tclHandle, "TclKit_SetKitPath", char * (*)(char *),
tclKit_SetKitPath);
if (tclKit_SetKitPath != NULL) {
/*
* XXX: Need to figure out how to populate dllFilename if
* NpLoadLibrary didn't do it for us on Unix.
*/
tclKit_SetKitPath(dllFilename);
}
}
}
if (tclKit_AppInit(g_Interp) != TCL_OK) {
const char *msg = Tcl_GetVar(g_Interp, "errorInfo", TCL_GLOBAL_ONLY);
warn("Failed to initialize Tcl with %s:\n%s",
(tclKit_AppInit == Tcl_Init) ? "Tcl_Init" : "TclKit_AppInit",
msg);
return TCL_ERROR;
}
/*
* Hold on to the interp handle until finalize, as special
* kit-based interps require the first initialized interp to
* remain alive.
*/
return TCL_OK;
}
#endif
#if DEBUG_REFCOUNTS
static void
check_refcounts(Tcl_Obj *objPtr) {
int rc = objPtr->refCount;
if (rc != 1) {
fprintf(stderr, "objPtr %p refcount %d\n", objPtr, rc); fflush(stderr);
}
if (objPtr->typePtr == tclListTypePtr) {
int objc, i;
Tcl_Obj **objv;
Tcl_ListObjGetElements(NULL, objPtr, &objc, &objv);
for (i = 0; i < objc; i++) {
check_refcounts(objv[i]);
}
}
}
#endif
static int
has_highbit(const char *s, int len)
{
const char *e = s + len;
while (s < e) {
if (*s++ & 0x80)
return 1;
}
return 0;
}
static SV *
SvFromTclObj(pTHX_ Tcl_Obj *objPtr)
{
SV *sv;
int len;
const char *str;
if (objPtr == NULL) {
/*
* Use newSV(0) instead of &PL_sv_undef as it may be stored in an AV.
* It also provides symmetry with the other newSV* calls below.
* This SV will also be mortalized later.
*/
sv = newSV(0);
}
/* Must check this now in case any tcl…TypePtr's are NULL */
else if (objPtr->typePtr == NULL) {
goto handle_as_string;
}
else if ((objPtr->typePtr == tclIntTypePtr) ||
(objPtr->typePtr == tclWideIntTypePtr)) {
/*
* Tcl TIP 484 means that value type "int" may be 64-bit
* even on 32-bit systems.
*/
Tcl_WideInt w;
Tcl_GetWideIntFromObj(NULL, objPtr, &w); /* must return TCL_OK */
if (IVSIZE >= sizeof(Tcl_WideInt) ||
(w >= (Tcl_WideInt)IV_MIN && w <= (Tcl_WideInt)IV_MAX)
) {
sv = newSViv(w);
} else if (w >= (Tcl_WideInt)UV_MIN && w <= (Tcl_WideInt)UV_MAX) {
sv = newSVuv(w);
} else {
goto handle_as_string;
}
}
else if (objPtr->typePtr == tclDoubleTypePtr) {
sv = newSVnv(objPtr->internalRep.doubleValue);
}
else if (objPtr->typePtr == tclBooleanTypePtr) {
/*
* Returning 0 or 1 to Perl is more useful than returning string boolean
* (i.e. "true"/"false"/"yes"/"no"/"on"/"off").
*/
int boolValue;
Tcl_GetBooleanFromObj(NULL, objPtr, &boolValue); /* must return TCL_OK */
sv = newSVsv(boolSV(boolValue));
}
else if (objPtr->typePtr == tclByteArrayTypePtr) {
str = (const char *) Tcl_GetByteArrayFromObj(objPtr, &len);
sv = newSVpvn(str, len);
}
else if (objPtr->typePtr == tclListTypePtr) {
/*
* tclListTypePtr should become an AV.
* This code needs to reconcile with G_ context in prepare_Tcl_result
* and user's expectations of how data will be passed in. The key is
* that a stringified-list and pure-list should be operable in the
* same way in Perl.
*
* We have to watch for "empty" lists, which could equate to the
* empty string. Tcl's literal object sharing means that "" could
* be typed as a list, although we don't want to see it that way.
* Just treat empty list objects as an empty (not undef) SV.
*/
int objc;
Tcl_Obj **objv;
Tcl_ListObjGetElements(NULL, objPtr, &objc, &objv);
if (objc) {
int i;
AV *av = newAV();
for (i = 0; i < objc; i++) {
av_push(av, SvFromTclObj(aTHX_ objv[i]));
}
sv = sv_bless(newRV_noinc((SV *) av), gv_stashpv("Tcl::List", 1));
}
else {
sv = newSVpvn("", 0);
}
}
/* tclStringTypePtr is true unicode */
/* may also be handling int/wideInt outside of [IV_MIN,UV_MAX] */
else {
handle_as_string:
str = Tcl_GetStringFromObj(objPtr, &len);
sv = newSVpvn(str, len);
/* should turn on, but let's check this first for efficiency */
if (len && has_highbit(str, len)) {
/*
* Tcl can encode NULL as overlong utf-8 \300\200 (\xC0\x80).
* Tcl itself doesn't require this, but some extensions do when
* they pass the string data to native C APIs (like strlen).
* Tk is the most notable case for this (calling out to native UI
* toolkit APIs that don't take counted strings).
* s/\300\200/\0/g
*/
char *nul_start;
STRLEN len;
char *s = SvPV(sv, len);
char *end = s + len;
while ((nul_start = memchr(s, '\300', len))) {
if (nul_start + 1 < end && nul_start[1] == '\200') {
/* found it */
nul_start[0] = '\0';
memmove(nul_start + 1, nul_start + 2,
end - (nul_start + 2));
len--;
end--;
*end = '\0';
SvCUR_set(sv, SvCUR(sv) - 1);
}
len -= (nul_start + 1) - s;
s = nul_start + 1;
}
SvUTF8_on(sv);
}
}
return sv;
}
/*
* Create a Tcl_Obj from a Perl SV.
* Return Tcl_Obj with refcount = 0. Caller should call Tcl_IncrRefCount
* or pass of to function that does (manage object lifetime).
*/
static Tcl_Obj *
TclObjFromSv(pTHX_ SV *sv)
{
Tcl_Obj *objPtr = NULL;
if (SvGMAGICAL(sv))
mg_get(sv);
if (!SvOK(sv)) {
objPtr = Tcl_NewObj();
}
else if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVAV &&
(!SvOBJECT(SvRV(sv)) || sv_isa(sv, "Tcl::List")))
{
/*
* Recurse into ARRAYs, turning them into Tcl list Objs
*/
SV **svp;
AV *av = (AV *) SvRV(sv);
I32 avlen = av_len(av);
int i;
objPtr = Tcl_NewListObj(0, (Tcl_Obj **) NULL);
for (i = 0; i <= avlen; i++) {
svp = av_fetch(av, i, FALSE);
if (svp == NULL) {
/* watch for sparse arrays - translate as empty element */
/* XXX: Is this handling refcount on NewObj right? */
Tcl_ListObjAppendElement(NULL, objPtr, Tcl_NewObj());
} else {
if (SvROK(*svp) && (AV *) SvRV(*svp) == av) {
/* XXX: Is this a proper check for cyclical reference? */
croak("cyclical array reference found");
abort();
}
Tcl_ListObjAppendElement(NULL, objPtr,
TclObjFromSv(aTHX_ sv_mortalcopy(*svp)));
}
}
}
else if (SvPOK(sv)) {
STRLEN length;
char *str = SvPV(sv, length);
/*
* Tcl's "String" object expects utf-8 strings. If we aren't sure
* that we have a utf-8 data, pass it as a Tcl ByteArray (C char*).
*
* XXX Possible optimization opportunity here. Tcl will actually
* XXX accept and handle most latin-1 char sequences correctly, but
* XXX not blocks of truly binary data. This code is 100% correct,
* XXX but could be tweaked to improve performance.
*/
if (SvUTF8(sv)) {
/*
* Tcl allows NULL to be encoded overlong as \300\200 (\xC0\x80).
* Tcl itself doesn't require this, but some extensions do when
* they pass the string data to native C APIs (like strlen).
* Tk is the most notable case for this (calling out to native UI
* toolkit APIs that don't take counted strings).
*/
if (memchr(str, '\0', length)) {
/* ($sv_copy = $sv) =~ s/\0/\300\200/g */
SV *sv_copy = sv_mortalcopy(sv);
STRLEN len;
char *s = SvPV(sv_copy, len);
char *nul;
while ((nul = memchr(s, '\0', len))) {
STRLEN i = nul - SvPVX(sv_copy);
s = SvGROW(sv_copy, SvCUR(sv_copy) + 2);
nul = s + i;
memmove(nul + 2, nul + 1, SvEND(sv_copy) - (nul + 1));
nul[0] = '\300';
nul[1] = '\200';
SvCUR_set(sv_copy, SvCUR(sv_copy) + 1);
s = nul + 2;
len = SvEND(sv_copy) - s;
}
str = SvPV(sv_copy, length);
}
objPtr = Tcl_NewStringObj(str, length);
} else {
objPtr = Tcl_NewByteArrayObj((unsigned char *)str, length);
}
}
else if (SvNOK(sv)) {
double dval = SvNV(sv);
int ival;
/*
* Perl does math with doubles by default, so 0 + 1 == 1.0.
* Check for int-equiv doubles and make those ints.
* XXX This check possibly only necessary for <=5.6.x
*/
if (((double)(ival = SvIV(sv)) == dval)) {
objPtr = Tcl_NewIntObj(ival);
} else {
objPtr = Tcl_NewDoubleObj(dval);
}
}
else if (SvIOK(sv)) {
objPtr = Tcl_NewIntObj(SvIV(sv));
}
else {
/*
* Catch-all
* XXX: Should we recurse other REFs, or better to stringify them?
*/
STRLEN length;
char *str = SvPV(sv, length);
/*
* Tcl's "String" object expects utf-8 strings. If we aren't sure
* that we have a utf-8 data, pass it as a Tcl ByteArray (C char*).
*/
if (SvUTF8(sv)) {
/*
* Should we consider overlong NULL encoding for Tcl here?
*/
objPtr = Tcl_NewStringObj(str, length);
} else {
objPtr = Tcl_NewByteArrayObj((unsigned char *) str, length);
}
}
return objPtr;
}
int Tcl_EvalInPerl(ClientData clientData, Tcl_Interp *interp,
int objc, Tcl_Obj *const objv[])
{
dTHX; /* fetch context */
dSP;
I32 count;
SV *sv;
int rc;
/*
* This is the command created in Tcl to eval stuff in Perl
*/
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "string");
}
ENTER;
SAVETMPS;
PUSHMARK(sp);
PUTBACK;
count = perl_eval_sv(sv_2mortal(SvFromTclObj(aTHX_ objv[1])),
G_EVAL|G_SCALAR);
SPAGAIN;
if (SvTRUE(ERRSV)) {
Tcl_SetResult(interp, SvPV_nolen(ERRSV), TCL_VOLATILE);
POPs; /* pop the undef off the stack */
rc = TCL_ERROR;
}
else {
if (count != 1) {
croak("Perl sub bound to Tcl proc returned %ld args, expected 1",
(long)count);
}
sv = POPs; /* pop the undef off the stack */
if (SvOK(sv)) {
Tcl_Obj *objPtr = TclObjFromSv(aTHX_ sv);
/* Tcl_SetObjResult will incr refcount */
Tcl_SetObjResult(interp, objPtr);
}
rc = TCL_OK;
}
PUTBACK;
/*
* If the routine returned undef, it indicates that it has done the
* SetResult itself and that we should return TCL_ERROR
*/
FREETMPS;
LEAVE;
return rc;
}
int Tcl_PerlCallWrapper(ClientData clientData, Tcl_Interp *interp,
int objc, Tcl_Obj *const objv[])
{
dTHX; /* fetch context */
dSP;
AV *av = (AV *) clientData;
I32 count;
SV *sv;
int flag;
int rc;
/*
* av = [$perlsub, $realclientdata, $interp, $deleteProc]
* (where $deleteProc is optional but we don't need it here anyway)
*/
if (AvFILL(av) != 3 && AvFILL(av) != 4)
croak("bad clientdata argument passed to Tcl_PerlCallWrapper");
flag = SvIV(*av_fetch(av, 3, FALSE));
ENTER;
SAVETMPS;
PUSHMARK(sp);
if (flag & 1) {
if (objc) {
objc--;
objv++;
EXTEND(sp, objc);
}
}
else {
EXTEND(sp, objc + 2);
/*
* Place clientData and original interp on the stack, then the
* Tcl object invoke list, including the command name. Users
* who only want the args from Tcl can splice off the first 3 args
*/
PUSHs(sv_mortalcopy(*av_fetch(av, 1, FALSE)));
PUSHs(sv_mortalcopy(*av_fetch(av, 2, FALSE)));
}
while (objc--) {
PUSHs(sv_2mortal(SvFromTclObj(aTHX_ *objv++)));
}
PUTBACK;
count = perl_call_sv(*av_fetch(av, 0, FALSE), G_EVAL|G_SCALAR);
SPAGAIN;
if (SvTRUE(ERRSV)) {
Tcl_SetResult(interp, SvPV_nolen(ERRSV), TCL_VOLATILE);
POPs; /* pop the undef off the stack */
rc = TCL_ERROR;
}
else {
if (count != 1) {
croak("Perl sub bound to Tcl proc returned %ld args, expected 1",
(long)count);
}
sv = POPs; /* pop the undef off the stack */
if (SvOK(sv)) {
Tcl_Obj *objPtr = TclObjFromSv(aTHX_ sv);
/* Tcl_SetObjResult will incr refcount */
Tcl_SetObjResult(interp, objPtr);
}
rc = TCL_OK;
}
PUTBACK;
/*
* If the routine returned undef, it indicates that it has done the
* SetResult itself and that we should return TCL_ERROR
*/
FREETMPS;
LEAVE;
return rc;
}
void
Tcl_PerlCallDeleteProc(ClientData clientData)
{
dTHX; /* fetch context */
AV *av = (AV *) clientData;
/*
* av = [$perlsub, $realclientdata, $interp, $deleteProc]
* (where $deleteProc is optional but we don't need it here anyway)
*/
if (AvFILL(av) == 4) {
dSP;
PUSHMARK(sp);
EXTEND(sp, 1);
PUSHs(sv_mortalcopy(*av_fetch(av, 1, FALSE)));
PUTBACK;
(void) perl_call_sv(*av_fetch(av, 4, FALSE), G_SCALAR|G_DISCARD);
}
else if (AvFILL(av) != 3) {
croak("bad clientdata argument passed to Tcl_PerlCallDeleteProc");
}
SvREFCNT_dec(av);
/* it got double tapped when it was made
ie AV *av = (AV *) SvREFCNT_inc((SV *) newAV());
so undouble tap it now
*/
SvREFCNT_dec(av);
}
void
prepare_Tcl_result(pTHX_ Tcl interp, char *caller)
{
dSP;
Tcl_Obj *objPtr, **objv;
int gimme, objc, i;
objPtr = Tcl_GetObjResult(interp);
gimme = GIMME_V;
if (gimme == G_SCALAR) {
/*
* This checks Tcl_Obj type. XPUSH not needed because we
* are called when there is enough space on the stack.
*/
PUSHs(sv_2mortal(SvFromTclObj(aTHX_ objPtr)));
}
else if (gimme == G_ARRAY) {
if (Tcl_ListObjGetElements(interp, objPtr, &objc, &objv)
!= TCL_OK) {
croak("%s called in list context did not return a valid Tcl list",
caller);
}
if (objc) {
EXTEND(sp, objc);
for (i = 0; i < objc; i++) {
/*
* This checks Tcl_Obj type
*/
PUSHs(sv_2mortal(SvFromTclObj(aTHX_ objv[i])));
}
}
}
else {
/* G_VOID context - ignore result */
}
PUTBACK;
return;
}
char *
var_trace(ClientData clientData, Tcl_Interp *interp,
char *name1, char *name2, int flags)
{
dTHX; /* fetch context */