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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
|
/*
* tclEvent.c --
*
* This file implements some general event related interfaces including
* background errors, exit handlers, and the "vwait" and "update" command
* functions.
*
* Copyright © 1990-1994 The Regents of the University of California.
* Copyright © 1994-1998 Sun Microsystems, Inc.
* Copyright © 2004 Zoran Vasiljevic.
*
* See the file "license.terms" for information on usage and redistribution of
* this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include "tclInt.h"
#include "tclUuid.h"
/*
* The data structure below is used to report background errors. One such
* structure is allocated for each error; it holds information about the
* interpreter and the error until an idle handler command can be invoked.
*/
typedef struct BgError {
Tcl_Obj *errorMsg; /* Copy of the error message (the interp's
* result when the error occurred). */
Tcl_Obj *returnOpts; /* Active return options when the error
* occurred */
struct BgError *nextPtr; /* Next in list of all pending error reports
* for this interpreter, or NULL for end of
* list. */
} BgError;
/*
* One of the structures below is associated with the "tclBgError" assoc data
* for each interpreter. It keeps track of the head and tail of the list of
* pending background errors for the interpreter.
*/
typedef struct {
Tcl_Interp *interp; /* Interpreter in which error occurred. */
Tcl_Obj *cmdPrefix; /* First word(s) of the handler command */
BgError *firstBgPtr; /* First in list of all background errors
* waiting to be processed for this
* interpreter (NULL if none). */
BgError *lastBgPtr; /* Last in list of all background errors
* waiting to be processed for this
* interpreter (NULL if none). */
} ErrAssocData;
/*
* For each "vwait" event source a structure of the following type
* is used:
*/
typedef struct {
int *donePtr; /* Pointer to flag to signal or NULL. */
int sequence; /* Order of occurrence. */
int mask; /* 0, or TCL_READABLE/TCL_WRITABLE. */
Tcl_Obj *sourceObj; /* Name of the event source, either a
* variable name or channel name. */
} VwaitItem;
/*
* For each exit handler created with a call to Tcl_Create(Late)ExitHandler
* there is a structure of the following type:
*/
typedef struct ExitHandler {
Tcl_ExitProc *proc; /* Function to call when process exits. */
void *clientData; /* One word of information to pass to proc. */
struct ExitHandler *nextPtr;/* Next in list of all exit handlers for this
* application, or NULL for end of list. */
} ExitHandler;
/*
* There is both per-process and per-thread exit handlers. The first list is
* controlled by a mutex. The other is in thread local storage.
*/
static ExitHandler *firstExitPtr = NULL;
/* First in list of all exit handlers for
* application. */
static ExitHandler *firstLateExitPtr = NULL;
/* First in list of all late exit handlers for
* application. */
TCL_DECLARE_MUTEX(exitMutex)
/*
* This variable is set to 1 when Tcl_Exit is called. The variable is checked
* by TclInExit() to allow different behavior for exit-time processing, e.g.,
* in closing of files and pipes.
*/
static int inExit = 0;
static int subsystemsInitialized = 0;
static const char ENCODING_ERROR[] = "\n\t(encoding error in stderr)";
/*
* This variable contains the application wide exit handler. It will be called
* by Tcl_Exit instead of the C-runtime exit if this variable is set to a
* non-NULL value.
*/
static TCL_NORETURN1 Tcl_ExitProc *appExitPtr = NULL;
typedef struct ThreadSpecificData {
ExitHandler *firstExitPtr; /* First in list of all exit handlers for this
* thread. */
int inExit; /* True when this thread is exiting. This is
* used as a hack to decide to close the
* standard channels. */
} ThreadSpecificData;
static Tcl_ThreadDataKey dataKey;
#if TCL_THREADS
typedef struct {
Tcl_ThreadCreateProc *proc; /* Main() function of the thread */
void *clientData; /* The one argument to Main() */
} ThreadClientData;
static Tcl_ThreadCreateType NewThreadProc(void *clientData);
#endif /* TCL_THREADS */
/*
* Prototypes for functions referenced only in this file:
*/
static void BgErrorDeleteProc(void *clientData,
Tcl_Interp *interp);
static void HandleBgErrors(void *clientData);
static void VwaitChannelReadProc(void *clientData, int mask);
static void VwaitChannelWriteProc(void *clientData, int mask);
static void VwaitTimeoutProc(void *clientData);
static char * VwaitVarProc(void *clientData,
Tcl_Interp *interp, const char *name1,
const char *name2, int flags);
static void InvokeExitHandlers(void);
static void FinalizeThread(int quick);
/*
*----------------------------------------------------------------------
*
* Tcl_BackgroundError --
*
* This function is invoked to handle errors that occur in Tcl commands
* that are invoked in "background" (e.g. from event or timer bindings).
*
* Results:
* None.
*
* Side effects:
* A handler command is invoked later as an idle handler to process the
* error, passing it the interp result and return options.
*
*----------------------------------------------------------------------
*/
#if !defined(TCL_NO_DEPRECATED) && TCL_MAJOR_VERSION < 9
#undef Tcl_BackgroundError
void
Tcl_BackgroundError(
Tcl_Interp *interp) /* Interpreter in which an error has
* occurred. */
{
Tcl_BackgroundException(interp, TCL_ERROR);
}
#endif /* TCL_NO_DEPRECATED */
void
Tcl_BackgroundException(
Tcl_Interp *interp, /* Interpreter in which an exception has
* occurred. */
int code) /* The exception code value */
{
BgError *errPtr;
ErrAssocData *assocPtr;
if (code == TCL_OK) {
return;
}
errPtr = (BgError*)ckalloc(sizeof(BgError));
errPtr->errorMsg = Tcl_GetObjResult(interp);
Tcl_IncrRefCount(errPtr->errorMsg);
errPtr->returnOpts = Tcl_GetReturnOptions(interp, code);
Tcl_IncrRefCount(errPtr->returnOpts);
errPtr->nextPtr = NULL;
(void) TclGetBgErrorHandler(interp);
assocPtr = (ErrAssocData *)Tcl_GetAssocData(interp, "tclBgError", NULL);
if (assocPtr->firstBgPtr == NULL) {
assocPtr->firstBgPtr = errPtr;
Tcl_DoWhenIdle(HandleBgErrors, assocPtr);
} else {
assocPtr->lastBgPtr->nextPtr = errPtr;
}
assocPtr->lastBgPtr = errPtr;
Tcl_ResetResult(interp);
}
/*
*----------------------------------------------------------------------
*
* HandleBgErrors --
*
* This function is invoked as an idle handler to process all of the
* accumulated background errors.
*
* Results:
* None.
*
* Side effects:
* Depends on what actions the handler command takes for the errors.
*
*----------------------------------------------------------------------
*/
static void
HandleBgErrors(
void *clientData) /* Pointer to ErrAssocData structure. */
{
ErrAssocData *assocPtr = (ErrAssocData *)clientData;
Tcl_Interp *interp = assocPtr->interp;
BgError *errPtr;
/*
* Not bothering to save/restore the interp state. Assume that any code
* that has interp state it needs to keep will make its own
* Tcl_SaveInterpState call before calling something like Tcl_DoOneEvent()
* that could lead us here.
*/
Tcl_Preserve(assocPtr);
Tcl_Preserve(interp);
while (assocPtr->firstBgPtr != NULL) {
int code;
Tcl_Size prefixObjc;
Tcl_Obj **prefixObjv, **tempObjv;
/*
* Note we copy the handler command prefix each pass through, so we do
* support one handler setting another handler.
*/
Tcl_Obj *copyObj = TclListObjCopy(NULL, assocPtr->cmdPrefix);
errPtr = assocPtr->firstBgPtr;
TclListObjGetElements(NULL, copyObj, &prefixObjc, &prefixObjv);
tempObjv = (Tcl_Obj**)ckalloc((prefixObjc+2) * sizeof(Tcl_Obj *));
memcpy(tempObjv, prefixObjv, prefixObjc*sizeof(Tcl_Obj *));
tempObjv[prefixObjc] = errPtr->errorMsg;
tempObjv[prefixObjc+1] = errPtr->returnOpts;
Tcl_AllowExceptions(interp);
code = Tcl_EvalObjv(interp, prefixObjc+2, tempObjv, TCL_EVAL_GLOBAL);
/*
* Discard the command and the information about the error report.
*/
Tcl_DecrRefCount(copyObj);
Tcl_DecrRefCount(errPtr->errorMsg);
Tcl_DecrRefCount(errPtr->returnOpts);
assocPtr->firstBgPtr = errPtr->nextPtr;
ckfree(errPtr);
ckfree(tempObjv);
if (code == TCL_BREAK) {
/*
* Break means cancel any remaining error reports for this
* interpreter.
*/
while (assocPtr->firstBgPtr != NULL) {
errPtr = assocPtr->firstBgPtr;
assocPtr->firstBgPtr = errPtr->nextPtr;
Tcl_DecrRefCount(errPtr->errorMsg);
Tcl_DecrRefCount(errPtr->returnOpts);
ckfree(errPtr);
}
} else if ((code == TCL_ERROR) && !Tcl_IsSafe(interp)) {
Tcl_Channel errChannel = Tcl_GetStdChannel(TCL_STDERR);
if (errChannel != NULL) {
Tcl_Obj *options = Tcl_GetReturnOptions(interp, code);
Tcl_Obj *keyPtr, *valuePtr = NULL;
TclNewLiteralStringObj(keyPtr, "-errorinfo");
Tcl_IncrRefCount(keyPtr);
Tcl_DictObjGet(NULL, options, keyPtr, &valuePtr);
Tcl_DecrRefCount(keyPtr);
Tcl_WriteChars(errChannel,
"error in background error handler:\n", -1);
if (valuePtr) {
if (Tcl_WriteObj(errChannel, valuePtr) < 0) {
Tcl_WriteChars(errChannel, ENCODING_ERROR, -1);
}
} else {
if (Tcl_WriteObj(errChannel, Tcl_GetObjResult(interp)) < 0) {
Tcl_WriteChars(errChannel, ENCODING_ERROR, -1);
}
}
Tcl_WriteChars(errChannel, "\n", 1);
Tcl_Flush(errChannel);
Tcl_DecrRefCount(options);
}
}
}
assocPtr->lastBgPtr = NULL;
Tcl_Release(interp);
Tcl_Release(assocPtr);
}
/*
*----------------------------------------------------------------------
*
* TclDefaultBgErrorHandlerObjCmd --
*
* This function is invoked to process the "::tcl::Bgerror" Tcl command.
* It is the default handler command registered with [interp bgerror] for
* the sake of compatibility with older Tcl releases.
*
* Results:
* A standard Tcl object result.
*
* Side effects:
* Depends on what actions the "bgerror" command takes for the errors.
*
*----------------------------------------------------------------------
*/
int
TclDefaultBgErrorHandlerObjCmd(
TCL_UNUSED(void *),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_Obj *keyPtr, *valuePtr;
Tcl_Obj *tempObjv[2];
int result, code, level;
Tcl_InterpState saved;
if (objc != 3) {
Tcl_WrongNumArgs(interp, 1, objv, "msg options");
return TCL_ERROR;
}
/*
* Check for a valid return options dictionary.
*/
TclNewLiteralStringObj(keyPtr, "-level");
Tcl_IncrRefCount(keyPtr);
result = Tcl_DictObjGet(NULL, objv[2], keyPtr, &valuePtr);
Tcl_DecrRefCount(keyPtr);
if (result != TCL_OK || valuePtr == NULL) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"missing return option \"-level\"", -1));
Tcl_SetErrorCode(interp, "TCL", "ARGUMENT", "MISSING", (void *)NULL);
return TCL_ERROR;
}
if (Tcl_GetIntFromObj(interp, valuePtr, &level) == TCL_ERROR) {
return TCL_ERROR;
}
TclNewLiteralStringObj(keyPtr, "-code");
Tcl_IncrRefCount(keyPtr);
result = Tcl_DictObjGet(NULL, objv[2], keyPtr, &valuePtr);
Tcl_DecrRefCount(keyPtr);
if (result != TCL_OK || valuePtr == NULL) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"missing return option \"-code\"", -1));
Tcl_SetErrorCode(interp, "TCL", "ARGUMENT", "MISSING", (void *)NULL);
return TCL_ERROR;
}
if (Tcl_GetIntFromObj(interp, valuePtr, &code) == TCL_ERROR) {
return TCL_ERROR;
}
if (level != 0) {
/*
* We're handling a TCL_RETURN exception.
*/
code = TCL_RETURN;
}
if (code == TCL_OK) {
/*
* Somehow we got to exception handling with no exception. (Pass
* TCL_OK to Tcl_BackgroundException()?) Just return without doing
* anything.
*/
return TCL_OK;
}
/*
* Construct the bgerror command.
*/
TclNewLiteralStringObj(tempObjv[0], "bgerror");
Tcl_IncrRefCount(tempObjv[0]);
/*
* Determine error message argument. Check the return options in case
* a non-error exception brought us here.
*/
switch (code) {
case TCL_ERROR:
tempObjv[1] = objv[1];
break;
case TCL_BREAK:
TclNewLiteralStringObj(tempObjv[1],
"invoked \"break\" outside of a loop");
break;
case TCL_CONTINUE:
TclNewLiteralStringObj(tempObjv[1],
"invoked \"continue\" outside of a loop");
break;
default:
tempObjv[1] = Tcl_ObjPrintf("command returned bad code: %d", code);
break;
}
Tcl_IncrRefCount(tempObjv[1]);
if (code != TCL_ERROR) {
Tcl_SetObjResult(interp, tempObjv[1]);
}
TclNewLiteralStringObj(keyPtr, "-errorcode");
Tcl_IncrRefCount(keyPtr);
result = Tcl_DictObjGet(NULL, objv[2], keyPtr, &valuePtr);
Tcl_DecrRefCount(keyPtr);
if (result == TCL_OK && valuePtr != NULL) {
Tcl_SetObjErrorCode(interp, valuePtr);
}
TclNewLiteralStringObj(keyPtr, "-errorinfo");
Tcl_IncrRefCount(keyPtr);
result = Tcl_DictObjGet(NULL, objv[2], keyPtr, &valuePtr);
Tcl_DecrRefCount(keyPtr);
if (result == TCL_OK && valuePtr != NULL) {
Tcl_AppendObjToErrorInfo(interp, valuePtr);
}
if (code == TCL_ERROR) {
Tcl_SetObjResult(interp, tempObjv[1]);
}
/*
* Save interpreter state so we can restore it if multiple handler
* attempts are needed.
*/
saved = Tcl_SaveInterpState(interp, code);
/*
* Invoke the bgerror command.
*/
Tcl_AllowExceptions(interp);
code = Tcl_EvalObjv(interp, 2, tempObjv, TCL_EVAL_GLOBAL);
if (code == TCL_ERROR) {
/*
* If the interpreter is safe, we look for a hidden command named
* "bgerror" and call that with the error information. Otherwise,
* simply ignore the error. The rationale is that this could be an
* error caused by a malicious applet trying to cause an infinite
* barrage of error messages. The hidden "bgerror" command can be used
* by a security policy to interpose on such attacks and e.g. kill the
* applet after a few attempts.
*/
if (Tcl_IsSafe(interp)) {
Tcl_RestoreInterpState(interp, saved);
TclObjInvoke(interp, 2, tempObjv, TCL_INVOKE_HIDDEN);
} else {
Tcl_Channel errChannel = Tcl_GetStdChannel(TCL_STDERR);
if (errChannel != NULL) {
Tcl_Obj *resultPtr = Tcl_GetObjResult(interp);
Tcl_IncrRefCount(resultPtr);
if (Tcl_FindCommand(interp, "bgerror", NULL,
TCL_GLOBAL_ONLY) == NULL) {
Tcl_RestoreInterpState(interp, saved);
if (Tcl_WriteObj(errChannel, Tcl_GetVar2Ex(interp,
"errorInfo", NULL, TCL_GLOBAL_ONLY)) < 0) {
Tcl_WriteChars(errChannel, ENCODING_ERROR, -1);
}
Tcl_WriteChars(errChannel, "\n", -1);
} else {
Tcl_DiscardInterpState(saved);
Tcl_WriteChars(errChannel, "bgerror failed to handle"
" background error.\n Original error: ", -1);
if (Tcl_WriteObj(errChannel, tempObjv[1]) < 0) {
Tcl_WriteChars(errChannel, ENCODING_ERROR, -1);
}
Tcl_WriteChars(errChannel, "\n Error in bgerror: ", -1);
if (Tcl_WriteObj(errChannel, resultPtr) < 0) {
Tcl_WriteChars(errChannel, ENCODING_ERROR, -1);
}
Tcl_WriteChars(errChannel, "\n", -1);
}
Tcl_DecrRefCount(resultPtr);
Tcl_Flush(errChannel);
} else {
Tcl_DiscardInterpState(saved);
}
}
code = TCL_OK;
} else {
Tcl_DiscardInterpState(saved);
}
Tcl_DecrRefCount(tempObjv[0]);
Tcl_DecrRefCount(tempObjv[1]);
Tcl_ResetResult(interp);
return code;
}
/*
*----------------------------------------------------------------------
*
* TclSetBgErrorHandler --
*
* This function sets the command prefix to be used to handle background
* errors in interp.
*
* Results:
* None.
*
* Side effects:
* Error handler is registered.
*
*----------------------------------------------------------------------
*/
void
TclSetBgErrorHandler(
Tcl_Interp *interp,
Tcl_Obj *cmdPrefix)
{
ErrAssocData *assocPtr = (ErrAssocData *)Tcl_GetAssocData(interp, "tclBgError", NULL);
if (cmdPrefix == NULL) {
Tcl_Panic("TclSetBgErrorHandler: NULL cmdPrefix argument");
}
if (assocPtr == NULL) {
/*
* First access: initialize.
*/
assocPtr = (ErrAssocData*)ckalloc(sizeof(ErrAssocData));
assocPtr->interp = interp;
assocPtr->cmdPrefix = NULL;
assocPtr->firstBgPtr = NULL;
assocPtr->lastBgPtr = NULL;
Tcl_SetAssocData(interp, "tclBgError", BgErrorDeleteProc, assocPtr);
}
if (assocPtr->cmdPrefix) {
Tcl_DecrRefCount(assocPtr->cmdPrefix);
}
assocPtr->cmdPrefix = cmdPrefix;
Tcl_IncrRefCount(assocPtr->cmdPrefix);
}
/*
*----------------------------------------------------------------------
*
* TclGetBgErrorHandler --
*
* This function retrieves the command prefix currently used to handle
* background errors in interp.
*
* Results:
* A (Tcl_Obj *) to a list of words (command prefix).
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
Tcl_Obj *
TclGetBgErrorHandler(
Tcl_Interp *interp)
{
ErrAssocData *assocPtr = (ErrAssocData *)Tcl_GetAssocData(interp, "tclBgError", NULL);
if (assocPtr == NULL) {
Tcl_Obj *bgerrorObj;
TclNewLiteralStringObj(bgerrorObj, "::tcl::Bgerror");
TclSetBgErrorHandler(interp, bgerrorObj);
assocPtr = (ErrAssocData *)Tcl_GetAssocData(interp, "tclBgError", NULL);
}
return assocPtr->cmdPrefix;
}
/*
*----------------------------------------------------------------------
*
* BgErrorDeleteProc --
*
* This function is associated with the "tclBgError" assoc data for an
* interpreter; it is invoked when the interpreter is deleted in order to
* free the information associated with any pending error reports.
*
* Results:
* None.
*
* Side effects:
* Background error information is freed: if there were any pending error
* reports, they are canceled.
*
*----------------------------------------------------------------------
*/
static void
BgErrorDeleteProc(
void *clientData, /* Pointer to ErrAssocData structure. */
TCL_UNUSED(Tcl_Interp *))
{
ErrAssocData *assocPtr = (ErrAssocData *)clientData;
BgError *errPtr;
while (assocPtr->firstBgPtr != NULL) {
errPtr = assocPtr->firstBgPtr;
assocPtr->firstBgPtr = errPtr->nextPtr;
Tcl_DecrRefCount(errPtr->errorMsg);
Tcl_DecrRefCount(errPtr->returnOpts);
ckfree(errPtr);
}
Tcl_CancelIdleCall(HandleBgErrors, assocPtr);
Tcl_DecrRefCount(assocPtr->cmdPrefix);
Tcl_EventuallyFree(assocPtr, TCL_DYNAMIC);
}
/*
*----------------------------------------------------------------------
*
* Tcl_CreateExitHandler --
*
* Arrange for a given function to be invoked just before the application
* exits.
*
* Results:
* None.
*
* Side effects:
* Proc will be invoked with clientData as argument when the application
* exits.
*
*----------------------------------------------------------------------
*/
void
Tcl_CreateExitHandler(
Tcl_ExitProc *proc, /* Function to invoke. */
void *clientData) /* Arbitrary value to pass to proc. */
{
ExitHandler *exitPtr = (ExitHandler*)ckalloc(sizeof(ExitHandler));
exitPtr->proc = proc;
exitPtr->clientData = clientData;
Tcl_MutexLock(&exitMutex);
exitPtr->nextPtr = firstExitPtr;
firstExitPtr = exitPtr;
Tcl_MutexUnlock(&exitMutex);
}
/*
*----------------------------------------------------------------------
*
* TclCreateLateExitHandler --
*
* Arrange for a given function to be invoked after all pre-thread
* cleanups.
*
* Results:
* None.
*
* Side effects:
* Proc will be invoked with clientData as argument when the application
* exits.
*
*----------------------------------------------------------------------
*/
void
TclCreateLateExitHandler(
Tcl_ExitProc *proc, /* Function to invoke. */
void *clientData) /* Arbitrary value to pass to proc. */
{
ExitHandler *exitPtr = (ExitHandler*)ckalloc(sizeof(ExitHandler));
exitPtr->proc = proc;
exitPtr->clientData = clientData;
Tcl_MutexLock(&exitMutex);
exitPtr->nextPtr = firstLateExitPtr;
firstLateExitPtr = exitPtr;
Tcl_MutexUnlock(&exitMutex);
}
/*
*----------------------------------------------------------------------
*
* Tcl_DeleteExitHandler --
*
* This function cancels an existing exit handler matching proc and
* clientData, if such a handler exits.
*
* Results:
* None.
*
* Side effects:
* If there is an exit handler corresponding to proc and clientData then
* it is canceled; if no such handler exists then nothing happens.
*
*----------------------------------------------------------------------
*/
void
Tcl_DeleteExitHandler(
Tcl_ExitProc *proc, /* Function that was previously registered. */
void *clientData) /* Arbitrary value to pass to proc. */
{
ExitHandler *exitPtr, *prevPtr;
Tcl_MutexLock(&exitMutex);
for (prevPtr = NULL, exitPtr = firstExitPtr; exitPtr != NULL;
prevPtr = exitPtr, exitPtr = exitPtr->nextPtr) {
if ((exitPtr->proc == proc)
&& (exitPtr->clientData == clientData)) {
if (prevPtr == NULL) {
firstExitPtr = exitPtr->nextPtr;
} else {
prevPtr->nextPtr = exitPtr->nextPtr;
}
ckfree(exitPtr);
break;
}
}
Tcl_MutexUnlock(&exitMutex);
return;
}
/*
*----------------------------------------------------------------------
*
* TclDeleteLateExitHandler --
*
* This function cancels an existing late exit handler matching proc and
* clientData, if such a handler exits.
*
* Results:
* None.
*
* Side effects:
* If there is a late exit handler corresponding to proc and clientData
* then it is canceled; if no such handler exists then nothing happens.
*
*----------------------------------------------------------------------
*/
void
TclDeleteLateExitHandler(
Tcl_ExitProc *proc, /* Function that was previously registered. */
void *clientData) /* Arbitrary value to pass to proc. */
{
ExitHandler *exitPtr, *prevPtr;
Tcl_MutexLock(&exitMutex);
for (prevPtr = NULL, exitPtr = firstLateExitPtr; exitPtr != NULL;
prevPtr = exitPtr, exitPtr = exitPtr->nextPtr) {
if ((exitPtr->proc == proc)
&& (exitPtr->clientData == clientData)) {
if (prevPtr == NULL) {
firstLateExitPtr = exitPtr->nextPtr;
} else {
prevPtr->nextPtr = exitPtr->nextPtr;
}
ckfree(exitPtr);
break;
}
}
Tcl_MutexUnlock(&exitMutex);
return;
}
/*
*----------------------------------------------------------------------
*
* Tcl_CreateThreadExitHandler --
*
* Arrange for a given function to be invoked just before the current
* thread exits.
*
* Results:
* None.
*
* Side effects:
* Proc will be invoked with clientData as argument when the application
* exits.
*
*----------------------------------------------------------------------
*/
void
Tcl_CreateThreadExitHandler(
Tcl_ExitProc *proc, /* Function to invoke. */
void *clientData) /* Arbitrary value to pass to proc. */
{
ExitHandler *exitPtr;
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
exitPtr = (ExitHandler*)ckalloc(sizeof(ExitHandler));
exitPtr->proc = proc;
exitPtr->clientData = clientData;
exitPtr->nextPtr = tsdPtr->firstExitPtr;
tsdPtr->firstExitPtr = exitPtr;
}
/*
*----------------------------------------------------------------------
*
* Tcl_DeleteThreadExitHandler --
*
* This function cancels an existing exit handler matching proc and
* clientData, if such a handler exits.
*
* Results:
* None.
*
* Side effects:
* If there is an exit handler corresponding to proc and clientData then
* it is canceled; if no such handler exists then nothing happens.
*
*----------------------------------------------------------------------
*/
void
Tcl_DeleteThreadExitHandler(
Tcl_ExitProc *proc, /* Function that was previously registered. */
void *clientData) /* Arbitrary value to pass to proc. */
{
ExitHandler *exitPtr, *prevPtr;
ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
for (prevPtr = NULL, exitPtr = tsdPtr->firstExitPtr; exitPtr != NULL;
prevPtr = exitPtr, exitPtr = exitPtr->nextPtr) {
if ((exitPtr->proc == proc)
&& (exitPtr->clientData == clientData)) {
if (prevPtr == NULL) {
tsdPtr->firstExitPtr = exitPtr->nextPtr;
} else {
prevPtr->nextPtr = exitPtr->nextPtr;
}
ckfree(exitPtr);
return;
}
}
}
/*
*----------------------------------------------------------------------
*
* Tcl_SetExitProc --
*
* This function sets the application wide exit handler that will be
* called by Tcl_Exit in place of the C-runtime exit. If the application
* wide exit handler is NULL, the C-runtime exit will be used instead.
*
* Results:
* The previously set application wide exit handler.
*
* Side effects:
* Sets the application wide exit handler to the specified value.
*
*----------------------------------------------------------------------
*/
Tcl_ExitProc *
Tcl_SetExitProc(
TCL_NORETURN1 Tcl_ExitProc *proc) /* New exit handler for app or NULL */
{
Tcl_ExitProc *prevExitProc;
/*
* Swap the old exit proc for the new one, saving the old one for our
* return value.
*/
Tcl_MutexLock(&exitMutex);
prevExitProc = appExitPtr;
appExitPtr = proc;
Tcl_MutexUnlock(&exitMutex);
return prevExitProc;
}
/*
*----------------------------------------------------------------------
*
* InvokeExitHandlers --
*
* Call the registered exit handlers.
*
* Results:
* None.
*
* Side effects:
* The exit handlers are invoked, and the ExitHandler struct is
* freed.
*
*----------------------------------------------------------------------
*/
static void
InvokeExitHandlers(void)
{
ExitHandler *exitPtr;
Tcl_MutexLock(&exitMutex);
inExit = 1;
for (exitPtr = firstExitPtr; exitPtr != NULL; exitPtr = firstExitPtr) {
/*
* Be careful to remove the handler from the list before invoking its
* callback. This protects us against double-freeing if the callback
* should call Tcl_DeleteExitHandler on itself.
*/
firstExitPtr = exitPtr->nextPtr;
Tcl_MutexUnlock(&exitMutex);
exitPtr->proc(exitPtr->clientData);
ckfree(exitPtr);
Tcl_MutexLock(&exitMutex);
}
firstExitPtr = NULL;
Tcl_MutexUnlock(&exitMutex);
}
/*
*----------------------------------------------------------------------
*
* Tcl_Exit --
*
* This function is called to terminate the application.
*
* Results:
* None.
*
* Side effects:
* All existing exit handlers are invoked, then the application ends.
*
*----------------------------------------------------------------------
*/
TCL_NORETURN void
Tcl_Exit(
int status) /* Exit status for application; typically 0
* for normal return, 1 for error return. */
{
TCL_NORETURN1 Tcl_ExitProc *currentAppExitPtr;
Tcl_MutexLock(&exitMutex);
currentAppExitPtr = appExitPtr;
Tcl_MutexUnlock(&exitMutex);
/*
* Warning: this function SHOULD NOT return, as there is code that depends
* on Tcl_Exit never returning. In fact, we will Tcl_Panic if anyone
* returns, so critical is this dependency.
*
* If subsystems are not (yet) initialized, proper Tcl-finalization is
* impossible, so fallback to system exit, see bug-[f8a33ce3db5d8cc2].
*/
if (currentAppExitPtr) {
currentAppExitPtr(INT2PTR(status));
} else if (subsystemsInitialized) {
if (TclFullFinalizationRequested()) {
/*
* Thorough finalization for Valgrind et al.
*/
Tcl_Finalize();
} else {
/*
* Fast and deterministic exit (default behavior)
*/
InvokeExitHandlers();
/*
* Ensure the thread-specific data is initialised as it is used in
* Tcl_FinalizeThread()
*/
(void) TCL_TSD_INIT(&dataKey);
/*
* Now finalize the calling thread only (others are not safely
* reachable). Among other things, this triggers a flush of the
* Tcl_Channels that may have data enqueued.
*/
FinalizeThread(/* quick */ 1);
}
}
TclpExit(status);
Tcl_Panic("OS exit failed!");
}
/*
*-------------------------------------------------------------------------
*
* Tcl_InitSubsystems --
*
* Initialize various subsytems in Tcl. This should be called the first
* time an interp is created, or before any of the subsystems are used.
* This function ensures an order for the initialization of subsystems:
*
* 1. that cannot be initialized in lazy order because they are mutually
* dependent.
*
* 2. so that they can be finalized in a known order w/o causing the
* subsequent re-initialization of a subsystem in the act of shutting
* down another.
*
* Results:
* The full Tcl version with build information.
*
* Side effects:
* Varied, see the respective initialization routines.
*
*-------------------------------------------------------------------------
*/
MODULE_SCOPE const TclStubs tclStubs;
#ifndef STRINGIFY
# define STRINGIFY(x) STRINGIFY1(x)
# define STRINGIFY1(x) #x
#endif
static const struct {
const TclStubs *stubs;
const char version[256];
} stubInfo = {
&tclStubs, {TCL_PATCH_LEVEL "+" STRINGIFY(TCL_VERSION_UUID)
#if defined(__clang__) && defined(__clang_major__)
".clang-" STRINGIFY(__clang_major__)
#if __clang_minor__ < 10
"0"
#endif
STRINGIFY(__clang_minor__)
#endif
#ifdef TCL_COMPILE_DEBUG
".compiledebug"
#endif
#ifdef TCL_COMPILE_STATS
".compilestats"
#endif
#if defined(__cplusplus) && !defined(__OBJC__)
".cplusplus"
#endif
#ifndef NDEBUG
".debug"
#endif
#if !defined(__clang__) && !defined(__INTEL_COMPILER) && defined(__GNUC__)
".gcc-" STRINGIFY(__GNUC__)
#if __GNUC_MINOR__ < 10
"0"
#endif
STRINGIFY(__GNUC_MINOR__)
#endif
#ifdef __INTEL_COMPILER
".icc-" STRINGIFY(__INTEL_COMPILER)
#endif
#if (defined(_WIN32) || (ULONG_MAX == 0xffffffffUL)) && !defined(_WIN64)
".ilp32"
#endif
#ifdef TCL_MEM_DEBUG
".memdebug"
#endif
#if defined(_MSC_VER)
".msvc-" STRINGIFY(_MSC_VER)
#endif
#ifdef USE_NMAKE
".nmake"
#endif
#ifdef TCL_NO_DEPRECATED
".no-deprecate"
#endif
#if !TCL_THREADS
".no-thread"
#endif
#ifndef TCL_CFG_OPTIMIZED
".no-optimize"
#endif
#ifdef __OBJC__
".objective-c"
#if defined(__cplusplus)
"plusplus"
#endif
#endif
#ifdef TCL_CFG_PROFILED
".profile"
#endif
#ifdef PURIFY
".purify"
#endif
#ifdef STATIC_BUILD
".static"
#endif
}};
const char *
Tcl_InitSubsystems(void)
{
if (inExit != 0) {
Tcl_Panic("Tcl_InitSubsystems called while exiting");
}
if (subsystemsInitialized == 0) {
/*
* Double check inside the mutex. There are definitely calls back into
* this routine from some of the functions below.
*/
TclpInitLock();
if (subsystemsInitialized == 0) {
/*
* Initialize locks used by the memory allocators before anything
* interesting happens so we can use the allocators in the
* implementation of self-initializing locks.
*/
TclInitThreadStorage(); /* Creates hash table for
* thread local storage */
#if defined(USE_TCLALLOC) && USE_TCLALLOC
TclInitAlloc(); /* Process wide mutex init */
#endif
#if TCL_THREADS && defined(USE_THREAD_ALLOC)
TclInitThreadAlloc(); /* Setup thread allocator caches */
#endif
#ifdef TCL_MEM_DEBUG
TclInitDbCkalloc(); /* Process wide mutex init */
#endif
TclpInitPlatform(); /* Creates signal handler(s) */
TclInitDoubleConversion(); /* Initializes constants for
* converting to/from double. */
TclInitObjSubsystem(); /* Register obj types, create
* mutexes. */
TclInitIOSubsystem(); /* Inits a tsd key (noop). */
TclInitEncodingSubsystem(); /* Process wide encoding init. */
TclInitNamespaceSubsystem();/* Register ns obj type (mutexed). */
subsystemsInitialized = 1;
}
TclpInitUnlock();
}
TclInitNotifier();
return stubInfo.version;
}
/*
*----------------------------------------------------------------------
*
* Tcl_Finalize --
*
* Shut down Tcl. First calls registered exit handlers, then carefully
* shuts down various subsystems. Should be invoked by user before the
* Tcl shared library is being unloaded in an embedded context.
*
* Results:
* None.
*
* Side effects:
* Varied, see the respective finalization routines.
*
*----------------------------------------------------------------------
*/
void
Tcl_Finalize(void)
{
ExitHandler *exitPtr;
/*
* Invoke exit handlers first.
*/
InvokeExitHandlers();
TclpInitLock();
if (subsystemsInitialized == 0) {
goto alreadyFinalized;
}
subsystemsInitialized = 0;
/*
* Ensure the thread-specific data is initialised as it is used in
* Tcl_FinalizeThread()
*/
(void) TCL_TSD_INIT(&dataKey);
/*
* Clean up after the current thread now, after exit handlers. In
* particular, the testexithandler command sets up something that writes
* to standard output, which gets closed. Note that there is no
* thread-local storage or IO subsystem after this call.
*/
Tcl_FinalizeThread();
/*
* Now invoke late (process-wide) exit handlers.
*/
Tcl_MutexLock(&exitMutex);
for (exitPtr = firstLateExitPtr; exitPtr != NULL;
exitPtr = firstLateExitPtr) {
/*
* Be careful to remove the handler from the list before invoking its
* callback. This protects us against double-freeing if the callback
* should call Tcl_DeleteLateExitHandler on itself.
*/
firstLateExitPtr = exitPtr->nextPtr;
Tcl_MutexUnlock(&exitMutex);
exitPtr->proc(exitPtr->clientData);
ckfree(exitPtr);
Tcl_MutexLock(&exitMutex);
}
firstLateExitPtr = NULL;
Tcl_MutexUnlock(&exitMutex);
/*
* Now finalize the Tcl execution environment. Note that this must be done
* after the exit handlers, because there are order dependencies.
*/
TclFinalizeEvaluation();
TclFinalizeExecution();
TclFinalizeEnvironment();
/*
* Finalizing the filesystem must come after anything which might
* conceivably interact with the 'Tcl_FS' API.
*/
TclFinalizeFilesystem();
/*
* Undo all Tcl_ObjType registrations, and reset the global list of free
* Tcl_Obj's. After this returns, no more Tcl_Obj's should be allocated or
* freed.
*
* Note in particular that TclFinalizeObjects() must follow
* TclFinalizeFilesystem() because TclFinalizeFilesystem free's the
* Tcl_Obj that holds the path of the current working directory.
*/
TclFinalizeObjects();
/*
* We must be sure the encoding finalization doesn't need to examine the
* filesystem in any way. Since it only needs to clean up internal data
* structures, this is fine.
*/
TclFinalizeEncodingSubsystem();
/*
* Repeat finalization of the thread local storage once more. Although
* this step is already done by the Tcl_FinalizeThread call above, series
* of events happening afterwards may re-initialize TSD slots. Those need
* to be finalized again, otherwise we're leaking memory chunks. Very
* important to note is that things happening afterwards should not
* reference anything which may re-initialize TSD's. This includes freeing
* Tcl_Objs's, among other things.
*
* This fixes the Tcl Bug #990552.
*/
TclFinalizeThreadData(/* quick */ 0);
/*
* Now we can free constants for conversions to/from double.
*/
TclFinalizeDoubleConversion();
/*
* There have been several bugs in the past that cause exit handlers to be
* established during Tcl_Finalize processing. Such exit handlers leave
* malloc'ed memory, and Tcl_FinalizeMemorySubsystem or
* Tcl_FinalizeThreadAlloc will result in a corrupted heap. The result can
* be a mysterious crash on process exit. Check here that nobody's done
* this.
*/
if (firstExitPtr != NULL) {
Tcl_Panic("exit handlers were created during Tcl_Finalize");
}
TclFinalizePreserve();
/*
* Free synchronization objects. There really should only be one thread
* alive at this moment.
*/
TclFinalizeSynchronization();
/*
* Close down the thread-specific object allocator.
*/
#if TCL_THREADS && defined(USE_THREAD_ALLOC)
TclFinalizeThreadAlloc();
#endif
/*
* We defer unloading of packages until very late to avoid memory access
* issues. Both exit callbacks and synchronization variables may be stored
* in packages.
*
* Note that TclFinalizeLoad unloads packages in the reverse of the order
* they were loaded in (i.e. last to be loaded is the first to be
* unloaded). This can be important for correct unloading when
* dependencies exist.
*
* Once load has been finalized, we will have deleted any temporary copies
* of shared libraries and can therefore reset the filesystem to its
* original state.
*/
TclFinalizeLoad();
TclResetFilesystem();
/*
* At this point, there should no longer be any ckalloc'ed memory.
*/
TclFinalizeMemorySubsystem();
alreadyFinalized:
TclFinalizeLock();
}
/*
*----------------------------------------------------------------------
*
* Tcl_FinalizeThread --
*
* Runs the exit handlers to allow Tcl to clean up its state about a
* particular thread.
*
* Results:
* None.
*
* Side effects:
* Varied, see the respective finalization routines.
*
*----------------------------------------------------------------------
*/
void
Tcl_FinalizeThread(void)
{
FinalizeThread(/* quick */ 0);
}
void
FinalizeThread(
int quick)
{
ExitHandler *exitPtr;
ThreadSpecificData *tsdPtr;
/*
* We use TclThreadDataKeyGet here, rather than Tcl_GetThreadData, because
* we don't want to initialize the data block if it hasn't been
* initialized already.
*/
tsdPtr = (ThreadSpecificData*)TclThreadDataKeyGet(&dataKey);
if (tsdPtr != NULL) {
tsdPtr->inExit = 1;
for (exitPtr = tsdPtr->firstExitPtr; exitPtr != NULL;
exitPtr = tsdPtr->firstExitPtr) {
/*
* Be careful to remove the handler from the list before invoking
* its callback. This protects us against double-freeing if the
* callback should call Tcl_DeleteThreadExitHandler on itself.
*/
tsdPtr->firstExitPtr = exitPtr->nextPtr;
exitPtr->proc(exitPtr->clientData);
ckfree(exitPtr);
}
TclFinalizeIOSubsystem();
TclFinalizeNotifier();
TclFinalizeAsync();
TclFinalizeThreadObjects();
}
/*
* Blow away all thread local storage blocks.
*
* Note that Tcl API allows creation of threads which do not use any Tcl
* interp or other Tcl subsytems. Those threads might, however, use thread
* local storage, so we must unconditionally finalize it.
*
* Fix [Bug #571002]
*/
TclFinalizeThreadData(quick);
}
/*
*----------------------------------------------------------------------
*
* TclInExit --
*
* Determines if we are in the middle of exit-time cleanup.
*
* Results:
* If we are in the middle of exiting, 1, otherwise 0.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
TclInExit(void)
{
return inExit;
}
/*
*----------------------------------------------------------------------
*
* TclInThreadExit --
*
* Determines if we are in the middle of thread exit-time cleanup.
*
* Results:
* If we are in the middle of exiting this thread, 1, otherwise 0.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
int
TclInThreadExit(void)
{
ThreadSpecificData *tsdPtr = (ThreadSpecificData *)TclThreadDataKeyGet(&dataKey);
if (tsdPtr == NULL) {
return 0;
}
return tsdPtr->inExit;
}
/*
*----------------------------------------------------------------------
*
* Tcl_VwaitObjCmd --
*
* This function is invoked to process the "vwait" Tcl command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
int
Tcl_VwaitObjCmd(
TCL_UNUSED(void *),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
int i, done = 0, timedOut = 0, foundEvent, any = 1, timeout = 0;
int numItems = 0, extended = 0, result, mode, mask = TCL_ALL_EVENTS;
Tcl_InterpState saved = NULL;
Tcl_TimerToken timer = NULL;
Tcl_Time before, after;
Tcl_Channel chan;
Tcl_WideInt diff = -1;
VwaitItem localItems[32], *vwaitItems = localItems;
static const char *const vWaitOptionStrings[] = {
"-all", "-extended", "-nofileevents", "-noidleevents",
"-notimerevents", "-nowindowevents", "-readable",
"-timeout", "-variable", "-writable", "--", NULL
};
enum vWaitOptions {
OPT_ALL, OPT_EXTD, OPT_NO_FEVTS, OPT_NO_IEVTS,
OPT_NO_TEVTS, OPT_NO_WEVTS, OPT_READABLE,
OPT_TIMEOUT, OPT_VARIABLE, OPT_WRITABLE, OPT_LAST
} index;
if ((objc == 2) && (strcmp(TclGetString(objv[1]), "--") != 0)) {
/*
* Legacy "vwait" syntax, skip option handling.
*/
i = 1;
goto endOfOptionLoop;
}
if ((unsigned) objc - 1 > sizeof(localItems) / sizeof(localItems[0])) {
vwaitItems = (VwaitItem *) ckalloc(sizeof(VwaitItem) * (objc - 1));
}
for (i = 1; i < objc; i++) {
const char *name;
name = TclGetString(objv[i]);
if (name[0] != '-') {
break;
}
if (Tcl_GetIndexFromObj(interp, objv[i], vWaitOptionStrings, "option", 0,
&index) != TCL_OK) {
result = TCL_ERROR;
goto done;
}
switch (index) {
case OPT_ALL:
any = 0;
break;
case OPT_EXTD:
extended = 1;
break;
case OPT_NO_FEVTS:
mask &= ~TCL_FILE_EVENTS;
break;
case OPT_NO_IEVTS:
mask &= ~TCL_IDLE_EVENTS;
break;
case OPT_NO_TEVTS:
mask &= ~TCL_TIMER_EVENTS;
break;
case OPT_NO_WEVTS:
mask &= ~TCL_WINDOW_EVENTS;
break;
case OPT_TIMEOUT:
if (++i >= objc) {
needArg:
Tcl_ResetResult(interp);
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"argument required for \"%s\"", vWaitOptionStrings[index]));
Tcl_SetErrorCode(interp, "TCL", "EVENT", "ARGUMENT", (void *)NULL);
result = TCL_ERROR;
goto done;
}
if (Tcl_GetIntFromObj(interp, objv[i], &timeout) != TCL_OK) {
result = TCL_ERROR;
goto done;
}
if (timeout < 0) {
Tcl_ResetResult(interp);
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"timeout must be positive", -1));
Tcl_SetErrorCode(interp, "TCL", "EVENT", "NEGTIME", (void *)NULL);
result = TCL_ERROR;
goto done;
}
break;
case OPT_LAST:
i++;
goto endOfOptionLoop;
case OPT_VARIABLE:
if (++i >= objc) {
goto needArg;
}
result = Tcl_TraceVar2(interp, TclGetString(objv[i]), NULL,
TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
VwaitVarProc, &vwaitItems[numItems]);
if (result != TCL_OK) {
goto done;
}
vwaitItems[numItems].donePtr = &done;
vwaitItems[numItems].sequence = -1;
vwaitItems[numItems].mask = 0;
vwaitItems[numItems].sourceObj = objv[i];
numItems++;
break;
case OPT_READABLE:
if (++i >= objc) {
goto needArg;
}
if (TclGetChannelFromObj(interp, objv[i], &chan, &mode, 0)
!= TCL_OK) {
result = TCL_ERROR;
goto done;
}
if (!(mode & TCL_READABLE)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"channel \"%s\" wasn't open for reading",
TclGetString(objv[i])));
result = TCL_ERROR;
goto done;
}
Tcl_CreateChannelHandler(chan, TCL_READABLE,
VwaitChannelReadProc, &vwaitItems[numItems]);
vwaitItems[numItems].donePtr = &done;
vwaitItems[numItems].sequence = -1;
vwaitItems[numItems].mask = TCL_READABLE;
vwaitItems[numItems].sourceObj = objv[i];
numItems++;
break;
case OPT_WRITABLE:
if (++i >= objc) {
goto needArg;
}
if (TclGetChannelFromObj(interp, objv[i], &chan, &mode, 0)
!= TCL_OK) {
result = TCL_ERROR;
goto done;
}
if (!(mode & TCL_WRITABLE)) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"channel \"%s\" wasn't open for writing",
TclGetString(objv[i])));
result = TCL_ERROR;
goto done;
}
Tcl_CreateChannelHandler(chan, TCL_WRITABLE,
VwaitChannelWriteProc, &vwaitItems[numItems]);
vwaitItems[numItems].donePtr = &done;
vwaitItems[numItems].sequence = -1;
vwaitItems[numItems].mask = TCL_WRITABLE;
vwaitItems[numItems].sourceObj = objv[i];
numItems++;
break;
}
}
endOfOptionLoop:
if ((mask & (TCL_FILE_EVENTS | TCL_IDLE_EVENTS |
TCL_TIMER_EVENTS | TCL_WINDOW_EVENTS)) == 0) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"can't wait: would block forever", -1));
Tcl_SetErrorCode(interp, "TCL", "EVENT", "NO_SOURCES", (void *)NULL);
result = TCL_ERROR;
goto done;
}
if ((timeout > 0) && ((mask & TCL_TIMER_EVENTS) == 0)) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"timer events disabled with timeout specified", -1));
Tcl_SetErrorCode(interp, "TCL", "EVENT", "NO_TIME", (void *)NULL);
result = TCL_ERROR;
goto done;
}
for (result = TCL_OK; i < objc; i++) {
result = Tcl_TraceVar2(interp, TclGetString(objv[i]), NULL,
TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
VwaitVarProc, &vwaitItems[numItems]);
if (result != TCL_OK) {
break;
}
vwaitItems[numItems].donePtr = &done;
vwaitItems[numItems].sequence = -1;
vwaitItems[numItems].mask = 0;
vwaitItems[numItems].sourceObj = objv[i];
numItems++;
}
if (result != TCL_OK) {
result = TCL_ERROR;
goto done;
}
if (!(mask & TCL_FILE_EVENTS)) {
for (i = 0; i < numItems; i++) {
if (vwaitItems[i].mask) {
Tcl_SetObjResult(interp, Tcl_NewStringObj(
"file events disabled with channel(s) specified", -1));
Tcl_SetErrorCode(interp, "TCL", "EVENT", "NO_FILE_EVENT", (void *)NULL);
result = TCL_ERROR;
goto done;
}
}
}
if (timeout > 0) {
vwaitItems[numItems].donePtr = &timedOut;
vwaitItems[numItems].sequence = -1;
vwaitItems[numItems].mask = 0;
vwaitItems[numItems].sourceObj = NULL;
timer = Tcl_CreateTimerHandler(timeout, VwaitTimeoutProc,
&vwaitItems[numItems]);
Tcl_GetTime(&before);
} else {
timeout = 0;
}
if ((numItems == 0) && (timeout == 0)) {
/*
* "vwait" is equivalent to "update",
* "vwait -nofileevents -notimerevents -nowindowevents"
* is equivalent to "update idletasks"
*/
any = 1;
mask |= TCL_DONT_WAIT;
}
foundEvent = 1;
while (!timedOut && foundEvent &&
((!any && (done < numItems)) || (any && !done))) {
foundEvent = Tcl_DoOneEvent(mask);
if (Tcl_Canceled(interp, TCL_LEAVE_ERR_MSG) == TCL_ERROR) {
break;
}
if (Tcl_LimitExceeded(interp)) {
Tcl_ResetResult(interp);
Tcl_SetObjResult(interp, Tcl_NewStringObj("limit exceeded", -1));
Tcl_SetErrorCode(interp, "TCL", "EVENT", "LIMIT", (void *)NULL);
break;
}
if ((numItems == 0) && (timeout == 0)) {
/*
* Behavior like "update": clear interpreter's result because
* event handlers could have executed commands.
*/
Tcl_ResetResult(interp);
result = TCL_OK;
goto done;
}
}
if (!foundEvent) {
Tcl_ResetResult(interp);
Tcl_SetObjResult(interp, Tcl_NewStringObj((numItems == 0) ?
"can't wait: would wait forever" :
"can't wait for variable(s)/channel(s): would wait forever",
-1));
Tcl_SetErrorCode(interp, "TCL", "EVENT", "NO_SOURCES", (void *)NULL);
result = TCL_ERROR;
goto done;
}
if (!done && !timedOut) {
/*
* The interpreter's result was already set to the right error message
* prior to exiting the loop above.
*/
result = TCL_ERROR;
goto done;
}
result = TCL_OK;
if (timeout <= 0) {
/*
* Clear out the interpreter's result, since it may have been set
* by event handlers.
*/
Tcl_ResetResult(interp);
goto done;
}
/*
* When timeout was specified, report milliseconds left or -1 on timeout.
*/
if (timedOut) {
diff = -1;
} else {
Tcl_GetTime(&after);
diff = after.sec * 1000 + after.usec / 1000;
diff -= before.sec * 1000 + before.usec / 1000;
diff = timeout - diff;
if (diff < 0) {
diff = 0;
}
}
done:
if ((timeout > 0) && (timer != NULL)) {
Tcl_DeleteTimerHandler(timer);
}
if (result != TCL_OK) {
saved = Tcl_SaveInterpState(interp, result);
}
for (i = 0; i < numItems; i++) {
if (vwaitItems[i].mask & TCL_READABLE) {
if (TclGetChannelFromObj(interp, vwaitItems[i].sourceObj,
&chan, &mode, 0) == TCL_OK) {
Tcl_DeleteChannelHandler(chan, VwaitChannelReadProc,
&vwaitItems[i]);
}
} else if (vwaitItems[i].mask & TCL_WRITABLE) {
if (TclGetChannelFromObj(interp, vwaitItems[i].sourceObj,
&chan, &mode, 0) == TCL_OK) {
Tcl_DeleteChannelHandler(chan, VwaitChannelWriteProc,
&vwaitItems[i]);
}
} else {
Tcl_UntraceVar2(interp, TclGetString(vwaitItems[i].sourceObj),
NULL, TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
VwaitVarProc, &vwaitItems[i]);
}
}
if (result == TCL_OK) {
if (extended) {
int k;
Tcl_Obj *listObj, *keyObj;
TclNewObj(listObj);
for (k = 0; k < done; k++) {
for (i = 0; i < numItems; i++) {
if (vwaitItems[i].sequence != k) {
continue;
}
if (vwaitItems[i].mask & TCL_READABLE) {
TclNewLiteralStringObj(keyObj, "readable");
} else if (vwaitItems[i].mask & TCL_WRITABLE) {
TclNewLiteralStringObj(keyObj, "writable");
} else {
TclNewLiteralStringObj(keyObj, "variable");
}
Tcl_ListObjAppendElement(NULL, listObj, keyObj);
Tcl_ListObjAppendElement(NULL, listObj,
vwaitItems[i].sourceObj);
}
}
if (timeout > 0) {
TclNewLiteralStringObj(keyObj, "timeleft");
Tcl_ListObjAppendElement(NULL, listObj, keyObj);
Tcl_ListObjAppendElement(NULL, listObj,
Tcl_NewWideIntObj(diff));
}
Tcl_SetObjResult(interp, listObj);
} else if (timeout > 0) {
Tcl_SetObjResult(interp, Tcl_NewWideIntObj(diff));
}
} else {
result = Tcl_RestoreInterpState(interp, saved);
}
if (vwaitItems != localItems) {
ckfree(vwaitItems);
}
return result;
}
static void
VwaitChannelReadProc(
void *clientData, /* Pointer to vwait info record. */
int mask) /* Event mask, must be TCL_READABLE. */
{
VwaitItem *itemPtr = (VwaitItem *) clientData;
if (!(mask & TCL_READABLE)) {
return;
}
if (itemPtr->donePtr != NULL) {
itemPtr->sequence = itemPtr->donePtr[0];
itemPtr->donePtr[0] += 1;
itemPtr->donePtr = NULL;
}
}
static void
VwaitChannelWriteProc(
void *clientData, /* Pointer to vwait info record. */
int mask) /* Event mask, must be TCL_WRITABLE. */
{
VwaitItem *itemPtr = (VwaitItem *) clientData;
if (!(mask & TCL_WRITABLE)) {
return;
}
if (itemPtr->donePtr != NULL) {
itemPtr->sequence = itemPtr->donePtr[0];
itemPtr->donePtr[0] += 1;
itemPtr->donePtr = NULL;
}
}
static void
VwaitTimeoutProc(
void *clientData) /* Pointer to vwait info record. */
{
VwaitItem *itemPtr = (VwaitItem *) clientData;
if (itemPtr->donePtr != NULL) {
itemPtr->donePtr[0] = 1;
itemPtr->donePtr = NULL;
}
}
static char *
VwaitVarProc(
void *clientData, /* Pointer to vwait info record. */
Tcl_Interp *interp, /* Interpreter containing variable. */
const char *name1, /* Name of variable. */
const char *name2, /* Second part of variable name. */
TCL_UNUSED(int) /*flags*/) /* Information about what happened. */
{
VwaitItem *itemPtr = (VwaitItem *) clientData;
if (itemPtr->donePtr != NULL) {
itemPtr->sequence = itemPtr->donePtr[0];
itemPtr->donePtr[0] += 1;
itemPtr->donePtr = NULL;
}
Tcl_UntraceVar2(interp, name1, name2, TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
VwaitVarProc, clientData);
return NULL;
}
/*
*----------------------------------------------------------------------
*
* Tcl_UpdateObjCmd --
*
* This function is invoked to process the "update" Tcl command. See the
* user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*----------------------------------------------------------------------
*/
int
Tcl_UpdateObjCmd(
TCL_UNUSED(void *),
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
int flags = 0; /* Initialized to avoid compiler warning. */
static const char *const updateOptions[] = {"idletasks", NULL};
enum updateOptionsEnum {OPT_IDLETASKS};
int optionIndex;
if (objc == 1) {
flags = TCL_ALL_EVENTS|TCL_DONT_WAIT;
} else if (objc == 2) {
if (Tcl_GetIndexFromObj(interp, objv[1], updateOptions,
"option", 0, &optionIndex) != TCL_OK) {
return TCL_ERROR;
}
switch ((enum updateOptionsEnum) optionIndex) {
case OPT_IDLETASKS:
flags = TCL_IDLE_EVENTS|TCL_DONT_WAIT;
break;
default:
Tcl_Panic("Tcl_UpdateObjCmd: bad option index to UpdateOptions");
}
} else {
Tcl_WrongNumArgs(interp, 1, objv, "?idletasks?");
return TCL_ERROR;
}
while (Tcl_DoOneEvent(flags) != 0) {
if (Tcl_Canceled(interp, TCL_LEAVE_ERR_MSG) == TCL_ERROR) {
return TCL_ERROR;
}
if (Tcl_LimitExceeded(interp)) {
Tcl_ResetResult(interp);
Tcl_SetObjResult(interp, Tcl_NewStringObj("limit exceeded", -1));
return TCL_ERROR;
}
}
/*
* Must clear the interpreter's result because event handlers could have
* executed commands.
*/
Tcl_ResetResult(interp);
return TCL_OK;
}
#if TCL_THREADS
/*
*----------------------------------------------------------------------
*
* NewThreadProc --
*
* Bootstrap function of a new Tcl thread.
*
* Results:
* None.
*
* Side Effects:
* Initializes Tcl notifier for the current thread.
*
*----------------------------------------------------------------------
*/
static Tcl_ThreadCreateType
NewThreadProc(
void *clientData)
{
ThreadClientData *cdPtr = (ThreadClientData *)clientData;
void *threadClientData;
Tcl_ThreadCreateProc *threadProc;
threadProc = cdPtr->proc;
threadClientData = cdPtr->clientData;
ckfree(clientData); /* Allocated in Tcl_CreateThread() */
threadProc(threadClientData);
TCL_THREAD_CREATE_RETURN;
}
#endif
/*
*----------------------------------------------------------------------
*
* Tcl_CreateThread --
*
* This function creates a new thread. This actually belongs to the
* tclThread.c file but since we use some private data structures local
* to this file, it is placed here.
*
* Results:
* TCL_OK if the thread could be created. The thread ID is returned in a
* parameter.
*
* Side effects:
* A new thread is created.
*
*----------------------------------------------------------------------
*/
int
Tcl_CreateThread(
Tcl_ThreadId *idPtr, /* Return, the ID of the thread */
Tcl_ThreadCreateProc *proc, /* Main() function of the thread */
void *clientData, /* The one argument to Main() */
TCL_HASH_TYPE stackSize, /* Size of stack for the new thread */
int flags) /* Flags controlling behaviour of the new
* thread. */
{
#if TCL_THREADS
ThreadClientData *cdPtr = (ThreadClientData *)ckalloc(sizeof(ThreadClientData));
int result;
cdPtr->proc = proc;
cdPtr->clientData = clientData;
result = TclpThreadCreate(idPtr, NewThreadProc, cdPtr, stackSize, flags);
if (result != TCL_OK) {
ckfree(cdPtr);
}
return result;
#else
(void)idPtr;
(void)proc;
(void)clientData;
(void)stackSize;
(void)flags;
return TCL_ERROR;
#endif /* TCL_THREADS */
}
/*
* Local Variables:
* mode: c
* c-basic-offset: 4
* fill-column: 78
* End:
*/
|