Debian Codegraph @

win/tclWinInit.c

raw
1 /*
2 * tclWinInit.c --
3 *
4 * Contains the Windows-specific interpreter initialization functions.
5 *
6 * Copyright (c) 1994-1997 Sun Microsystems, Inc.
7 * Copyright (c) 1998-1999 Scriptics Corporation.
8 * All rights reserved.
9 *
10 * See the file "license.terms" for information on usage and redistribution of
11 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
12 */
13
14 #include "tclWinInt.h"
15 #include <winnt.h>
16 #include <winbase.h>
17 #include <lmcons.h>
18
19 /*
20 * GetUserNameW() is found in advapi32.dll
21 */
22 #ifdef _MSC_VER
23 # pragma comment(lib, "advapi32.lib")
24 #endif
25
26 /*
27 * The following declaration is a workaround for some Microsoft brain damage.
28 * The SYSTEM_INFO structure is different in various releases, even though the
29 * layout is the same. So we overlay our own structure on top of it so we can
30 * access the interesting slots in a uniform way.
31 */
32
33 typedef struct {
34 WORD wProcessorArchitecture;
35 WORD wReserved;
36 } OemId;
37
38 /*
39 * Windows version dependend functions
40 */
41 TclWinProcs tclWinProcs;
42
43 /*
44 * The following arrays contain the human readable strings for the
45 * processor values.
46 */
47
48 #define NUMPROCESSORS 15
49 static const char *const processors[NUMPROCESSORS] = {
50 "intel", "mips", "alpha", "ppc", "shx", "arm", "ia64", "alpha64", "msil",
51 "amd64", "ia32_on_win64", "neutral", "arm64", "arm32_on_win64",
52 "ia32_on_arm64"
53 };
54
55 /*
56 * Forward declarations
57 */
58
59 static TclInitProcessGlobalValueProc InitializeDefaultLibraryDir;
60 static TclInitProcessGlobalValueProc InitializeSourceLibraryDir;
61 static void AppendEnvironment(Tcl_Obj *listPtr, const char *lib);
62
63 /*
64 * The default directory in which the init.tcl file is expected to be found.
65 */
66
67 static ProcessGlobalValue defaultLibraryDir =
68 {0, 0, NULL, NULL, InitializeDefaultLibraryDir, NULL, NULL};
69 static ProcessGlobalValue sourceLibraryDir =
70 {0, 0, NULL, NULL, InitializeSourceLibraryDir, NULL, NULL};
71
72 /*
73 *---------------------------------------------------------------------------
74 *
75 * TclpInitPlatform --
76 *
77 * Initialize all the platform-dependent things like signals,
78 * floating-point error handling and sockets.
79 *
80 * Called at process initialization time.
81 *
82 * Results:
83 * None.
84 *
85 * Side effects:
86 * None.
87 *
88 *---------------------------------------------------------------------------
89 */
90
91 void
92 TclpInitPlatform(void)
93 {
94 WSADATA wsaData;
95 WORD wVersionRequested = MAKEWORD(2, 2);
96 HMODULE handle;
97
98 tclPlatform = TCL_PLATFORM_WINDOWS;
99
100 /*
101 * Initialize the winsock library. On Windows XP and higher this
102 * can never fail.
103 */
104 WSAStartup(wVersionRequested, &wsaData);
105
106 #ifdef STATIC_BUILD
107 /*
108 * If we are in a statically linked executable, then we need to explicitly
109 * initialize the Windows function tables here since DllMain() will not be
110 * invoked.
111 */
112
113 TclWinInit(GetModuleHandleW(NULL));
114 #endif
115
116 /*
117 * Fill available functions depending on windows version
118 */
119 handle = GetModuleHandleW(L"KERNEL32");
120 tclWinProcs.cancelSynchronousIo =
121 (BOOL (WINAPI *)(HANDLE))(void *)GetProcAddress(handle,
122 "CancelSynchronousIo");
123 tclWinProcs.createSymbolicLink =
124 (BOOLEAN (WINAPI *)(LPCWSTR, LPCWSTR, DWORD))(void *)GetProcAddress(handle,
125 "CreateSymbolicLinkW");
126 }
127
128 /*
129 *-------------------------------------------------------------------------
130 *
131 * TclpInitLibraryPath --
132 *
133 * This is the fallback routine that sets the library path if the
134 * application has not set one by the first time it is needed.
135 *
136 * Results:
137 * None.
138 *
139 * Side effects:
140 * Sets the library path to an initial value.
141 *
142 *-------------------------------------------------------------------------
143 */
144
145 void
146 TclpInitLibraryPath(
147 char **valuePtr,
148 int *lengthPtr,
149 Tcl_Encoding *encodingPtr)
150 {
151 #define LIBRARY_SIZE 64
152 Tcl_Obj *pathPtr;
153 char installLib[LIBRARY_SIZE];
154 const char *bytes;
155 int length;
156
157 TclNewObj(pathPtr);
158
159 /*
160 * Initialize the substring used when locating the script library. The
161 * installLib variable computes the script library path relative to the
162 * installed DLL.
163 */
164
165 snprintf(installLib, sizeof(installLib), "lib/tcl%s", TCL_VERSION);
166
167 /*
168 * Look for the library relative to the TCL_LIBRARY env variable. If the
169 * last dirname in the TCL_LIBRARY path does not match the last dirname in
170 * the installLib variable, use the last dir name of installLib in
171 * addition to the original TCL_LIBRARY path.
172 */
173
174 AppendEnvironment(pathPtr, installLib);
175
176 /*
177 * Look for the library in its default location.
178 */
179
180 Tcl_ListObjAppendElement(NULL, pathPtr,
181 TclGetProcessGlobalValue(&defaultLibraryDir));
182
183 /*
184 * Look for the library in its source checkout location.
185 */
186
187 Tcl_ListObjAppendElement(NULL, pathPtr,
188 TclGetProcessGlobalValue(&sourceLibraryDir));
189
190 *encodingPtr = NULL;
191 bytes = TclGetStringFromObj(pathPtr, &length);
192 *lengthPtr = length++;
193 *valuePtr = (char *)ckalloc(length);
194 memcpy(*valuePtr, bytes, length);
195 Tcl_DecrRefCount(pathPtr);
196 }
197
198 /*
199 *---------------------------------------------------------------------------
200 *
201 * AppendEnvironment --
202 *
203 * Append the value of the TCL_LIBRARY environment variable onto the path
204 * pointer. If the env variable points to another version of tcl (e.g.
205 * "tcl9.0") also append the path to this version (e.g.,
206 * "tcl9.0/../tcl8.6")
207 *
208 * Results:
209 * None.
210 *
211 * Side effects:
212 * None.
213 *
214 *---------------------------------------------------------------------------
215 */
216
217 static void
218 AppendEnvironment(
219 Tcl_Obj *pathPtr,
220 const char *lib)
221 {
222 int pathc;
223 WCHAR wBuf[MAX_PATH];
224 DWORD dw;
225 char buf[MAX_PATH * 3];
226 Tcl_Obj *objPtr;
227 Tcl_DString ds;
228 const char **pathv;
229 char *shortlib;
230
231 /*
232 * The shortlib value needs to be the tail component of the lib path. For
233 * example, "lib/tcl8.6" -> "tcl8.6" while "usr/share/tcl8.6" -> "tcl8.6".
234 */
235
236 for (shortlib = (char *) &lib[strlen(lib)-1]; shortlib>lib ; shortlib--) {
237 if (*shortlib == '/') {
238 if ((size_t)(shortlib - lib) == strlen(lib) - 1) {
239 Tcl_Panic("last character in lib cannot be '/'");
240 }
241 shortlib++;
242 break;
243 }
244 }
245 if (shortlib == lib) {
246 Tcl_Panic("no '/' character found in lib");
247 }
248
249 dw = GetEnvironmentVariableW(L"TCL_LIBRARY", wBuf, MAX_PATH);
250 if (dw <= 0 || dw >= MAX_PATH) {
251 return;
252 }
253 if (WideCharToMultiByte(
254 CP_UTF8, 0, wBuf, -1, buf, MAX_PATH * 3, NULL, NULL) == 0) {
255 return;
256 }
257
258 if (buf[0] != '\0') {
259 objPtr = Tcl_NewStringObj(buf, -1);
260 Tcl_ListObjAppendElement(NULL, pathPtr, objPtr);
261
262 TclWinNoBackslash(buf);
263 Tcl_SplitPath(buf, &pathc, &pathv);
264
265 /*
266 * The lstrcmpiA() will work even if pathv[pathc-1] is random UTF-8
267 * chars because I know shortlib is ascii.
268 */
269
270 if ((pathc > 0) && (lstrcmpiA(shortlib, pathv[pathc - 1]) != 0)) {
271 /*
272 * TCL_LIBRARY is set but refers to a different tcl installation
273 * than the current version. Try fiddling with the specified
274 * directory to make it refer to this installation by removing the
275 * old "tclX.Y" and substituting the current version string.
276 */
277
278 pathv[pathc - 1] = shortlib;
279 Tcl_DStringInit(&ds);
280 (void) Tcl_JoinPath(pathc, pathv, &ds);
281 objPtr = TclDStringToObj(&ds);
282 } else {
283 objPtr = Tcl_NewStringObj(buf, -1);
284 }
285 Tcl_ListObjAppendElement(NULL, pathPtr, objPtr);
286 ckfree(pathv);
287 }
288 }
289
290 /*
291 *---------------------------------------------------------------------------
292 *
293 * InitializeDefaultLibraryDir --
294 *
295 * Locate the Tcl script library default location relative to the
296 * location of the Tcl DLL.
297 *
298 * Results:
299 * None.
300 *
301 * Side effects:
302 * None.
303 *
304 *---------------------------------------------------------------------------
305 */
306
307 static void
308 InitializeDefaultLibraryDir(
309 char **valuePtr,
310 int *lengthPtr,
311 Tcl_Encoding *encodingPtr)
312 {
313 HMODULE hModule = (HMODULE)TclWinGetTclInstance();
314 WCHAR wName[MAX_PATH + LIBRARY_SIZE];
315 char name[(MAX_PATH + LIBRARY_SIZE) * 3];
316 char *end, *p;
317
318 GetModuleFileNameW(hModule, wName, sizeof(wName)/sizeof(WCHAR));
319 WideCharToMultiByte(CP_UTF8, 0, wName, -1, name, sizeof(name), NULL, NULL);
320
321 end = strrchr(name, '\\');
322 *end = '\0';
323 p = strrchr(name, '\\');
324 if (p != NULL) {
325 end = p;
326 }
327 *end = '\\';
328
329 TclWinNoBackslash(name);
330 snprintf(end + 1, LIBRARY_SIZE, "lib/tcl%s", TCL_VERSION);
331 *lengthPtr = strlen(name);
332 *valuePtr = (char *)ckalloc(*lengthPtr + 1);
333 *encodingPtr = NULL;
334 memcpy(*valuePtr, name, *lengthPtr + 1);
335 }
336
337 /*
338 *---------------------------------------------------------------------------
339 *
340 * InitializeSourceLibraryDir --
341 *
342 * Locate the Tcl script library default location relative to the
343 * location of the Tcl DLL as it exists in the build output directory
344 * associated with the source checkout.
345 *
346 * Results:
347 * None.
348 *
349 * Side effects:
350 * None.
351 *
352 *---------------------------------------------------------------------------
353 */
354
355 static void
356 InitializeSourceLibraryDir(
357 char **valuePtr,
358 int *lengthPtr,
359 Tcl_Encoding *encodingPtr)
360 {
361 HMODULE hModule = (HMODULE)TclWinGetTclInstance();
362 WCHAR wName[MAX_PATH + LIBRARY_SIZE];
363 char name[(MAX_PATH + LIBRARY_SIZE) * 3];
364 char *end, *p;
365
366 GetModuleFileNameW(hModule, wName, sizeof(wName)/sizeof(WCHAR));
367 WideCharToMultiByte(CP_UTF8, 0, wName, -1, name, sizeof(name), NULL, NULL);
368
369 end = strrchr(name, '\\');
370 *end = '\0';
371 p = strrchr(name, '\\');
372 if (p != NULL) {
373 end = p;
374 }
375 *end = '\\';
376
377 TclWinNoBackslash(name);
378 snprintf(end + 1, LIBRARY_SIZE, "../library");
379 *lengthPtr = strlen(name);
380 *valuePtr = (char *)ckalloc(*lengthPtr + 1);
381 *encodingPtr = NULL;
382 memcpy(*valuePtr, name, *lengthPtr + 1);
383 }
384
385 /*
386 *---------------------------------------------------------------------------
387 *
388 * TclpSetInitialEncodings --
389 *
390 * Based on the locale, determine the encoding of the operating system
391 * and the default encoding for newly opened files.
392 *
393 * Called at process initialization time, and part way through startup,
394 * we verify that the initial encodings were correctly setup. Depending
395 * on Tcl's environment, there may not have been enough information first
396 * time through (above).
397 *
398 * Results:
399 * None.
400 *
401 * Side effects:
402 * The Tcl library path is converted from native encoding to UTF-8, on
403 * the first call, and the encodings may be changed on first or second
404 * call.
405 *
406 *---------------------------------------------------------------------------
407 */
408
409 void
410 TclpSetInitialEncodings(void)
411 {
412 Tcl_DString encodingName;
413
414 Tcl_SetSystemEncoding(NULL,
415 Tcl_GetEncodingNameFromEnvironment(&encodingName));
416 Tcl_DStringFree(&encodingName);
417 }
418
419 void TclWinSetInterfaces(
420 int dummy) /* Not used. */
421 {
422 (void)dummy;
423 }
424
425 const char *
426 Tcl_GetEncodingNameFromEnvironment(
427 Tcl_DString *bufPtr)
428 {
429 UINT acp = GetACP();
430
431 Tcl_DStringInit(bufPtr);
432 if (acp == CP_UTF8) {
433 Tcl_DStringAppend(bufPtr, "utf-8", 5);
434 } else {
435 Tcl_DStringSetLength(bufPtr, 2 + TCL_INTEGER_SPACE);
436 snprintf(Tcl_DStringValue(bufPtr), 2 + TCL_INTEGER_SPACE, "cp%d", acp);
437 Tcl_DStringSetLength(bufPtr, strlen(Tcl_DStringValue(bufPtr)));
438 }
439 return Tcl_DStringValue(bufPtr);
440 }
441
442 const char *
443 TclpGetUserName(
444 Tcl_DString *bufferPtr) /* Uninitialized or free DString filled with
445 * the name of user. */
446 {
447 Tcl_DStringInit(bufferPtr);
448
449 if (TclGetEnv("USERNAME", bufferPtr) == NULL) {
450 WCHAR szUserName[UNLEN+1];
451 DWORD cchUserNameLen = UNLEN;
452
453 if (!GetUserNameW(szUserName, &cchUserNameLen)) {
454 return NULL;
455 }
456 cchUserNameLen--;
457 cchUserNameLen *= sizeof(WCHAR);
458 Tcl_WinTCharToUtf((TCHAR *)szUserName, cchUserNameLen, bufferPtr);
459 }
460 return Tcl_DStringValue(bufferPtr);
461 }
462
463 /*
464 *---------------------------------------------------------------------------
465 *
466 * TclpSetVariables --
467 *
468 * Performs platform-specific interpreter initialization related to the
469 * tcl_platform and env variables, and other platform-specific things.
470 *
471 * Results:
472 * None.
473 *
474 * Side effects:
475 * Sets "tcl_platform", and "env(HOME)" Tcl variables.
476 *
477 *----------------------------------------------------------------------
478 */
479
480 void
481 TclpSetVariables(
482 Tcl_Interp *interp) /* Interp to initialize. */
483 {
484 typedef int(__stdcall getVersionProc)(void *);
485 const char *ptr;
486 char buffer[TCL_INTEGER_SPACE * 2];
487 union {
488 SYSTEM_INFO info;
489 OemId oemId;
490 } sys;
491 static OSVERSIONINFOW osInfo;
492 static int osInfoInitialized = 0;
493 Tcl_DString ds;
494
495 Tcl_SetVar2Ex(interp, "tclDefaultLibrary", NULL,
496 TclGetProcessGlobalValue(&defaultLibraryDir), TCL_GLOBAL_ONLY);
497
498 if (!osInfoInitialized) {
499 HMODULE handle = GetModuleHandleW(L"NTDLL");
500 getVersionProc *getVersion = (getVersionProc *) (void *)
501 GetProcAddress(handle, "RtlGetVersion");
502
503 osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
504 if (!getVersion || getVersion(&osInfo)) {
505 GetVersionExW(&osInfo);
506 }
507 osInfoInitialized = 1;
508 }
509 GetSystemInfo(&sys.info);
510
511 /*
512 * Define the tcl_platform array.
513 */
514
515 Tcl_SetVar2(interp, "tcl_platform", "platform", "windows",
516 TCL_GLOBAL_ONLY);
517 Tcl_SetVar2(interp, "tcl_platform", "os", "Windows NT", TCL_GLOBAL_ONLY);
518 if (osInfo.dwMajorVersion == 10 && osInfo.dwBuildNumber >= 22000) {
519 osInfo.dwMajorVersion = 11;
520 }
521 snprintf(buffer, sizeof(buffer), "%ld.%ld",
522 osInfo.dwMajorVersion, osInfo.dwMinorVersion);
523 Tcl_SetVar2(interp, "tcl_platform", "osVersion", buffer, TCL_GLOBAL_ONLY);
524 if (sys.oemId.wProcessorArchitecture < NUMPROCESSORS) {
525 Tcl_SetVar2(interp, "tcl_platform", "machine",
526 processors[sys.oemId.wProcessorArchitecture],
527 TCL_GLOBAL_ONLY);
528 }
529
530 #ifndef NDEBUG
531 /*
532 * The existence of the "debug" element of the tcl_platform array
533 * indicates that this particular Tcl shell has been compiled with debug
534 * information. Using "info exists tcl_platform(debug)" a Tcl script can
535 * direct the interpreter to load debug versions of DLLs with the load
536 * command.
537 */
538
539 Tcl_SetVar2(interp, "tcl_platform", "debug", "1",
540 TCL_GLOBAL_ONLY);
541 #endif
542
543 /*
544 * Set up the HOME environment variable from the HOMEDRIVE & HOMEPATH
545 * environment variables, if necessary.
546 */
547
548 Tcl_DStringInit(&ds);
549 ptr = Tcl_GetVar2(interp, "env", "HOME", TCL_GLOBAL_ONLY);
550 if (ptr == NULL) {
551 ptr = Tcl_GetVar2(interp, "env", "HOMEDRIVE", TCL_GLOBAL_ONLY);
552 if (ptr != NULL) {
553 Tcl_DStringAppend(&ds, ptr, -1);
554 }
555 ptr = Tcl_GetVar2(interp, "env", "HOMEPATH", TCL_GLOBAL_ONLY);
556 if (ptr != NULL) {
557 Tcl_DStringAppend(&ds, ptr, -1);
558 }
559 if (Tcl_DStringLength(&ds) > 0) {
560 Tcl_SetVar2(interp, "env", "HOME", Tcl_DStringValue(&ds),
561 TCL_GLOBAL_ONLY);
562 } else {
563 /* None of HOME, HOMEDRIVE, HOMEPATH exists. Try USERPROFILE */
564 ptr = Tcl_GetVar2(interp, "env", "USERPROFILE", TCL_GLOBAL_ONLY);
565 if (ptr != NULL && ptr[0]) {
566 Tcl_SetVar2(interp, "env", "HOME", ptr, TCL_GLOBAL_ONLY);
567 } else {
568 /* Last resort */
569 Tcl_SetVar2(interp, "env", "HOME", "c:\\", TCL_GLOBAL_ONLY);
570 }
571 }
572 }
573
574 /*
575 * Initialize the user name from the environment first, since this is much
576 * faster than asking the system.
577 * Note: cchUserNameLen is number of characters including nul terminator.
578 */
579
580 ptr = TclpGetUserName(&ds);
581 Tcl_SetVar2(interp, "tcl_platform", "user", ptr ? ptr : "",
582 TCL_GLOBAL_ONLY);
583 Tcl_DStringFree(&ds);
584
585 /*
586 * Define what the platform PATH separator is. [TIP #315]
587 */
588
589 Tcl_SetVar2(interp, "tcl_platform", "pathSeparator", ";", TCL_GLOBAL_ONLY);
590 }
591
592 /*
593 *----------------------------------------------------------------------
594 *
595 * TclpFindVariable --
596 *
597 * Locate the entry in environ for a given name. On Unix this routine is
598 * case sensitive, on Windows this matches mixed case.
599 *
600 * Results:
601 * The return value is the index in environ of an entry with the name
602 * "name", or -1 if there is no such entry. The integer
603 * at *lengthPtr is filled in with the length of name (if a matching
604 * entry is found) or the length of the environ array (if no
605 * matching entry is found).
606 *
607 * Side effects:
608 * None.
609 *
610 *----------------------------------------------------------------------
611 */
612
613 int
614 TclpFindVariable(
615 const char *name, /* Name of desired environment variable
616 * (UTF-8). */
617 int *lengthPtr) /* Used to return length of name (for
618 * successful searches) or number of non-NULL
619 * entries in environ (for unsuccessful
620 * searches). */
621 {
622 int i, length, result = -1;
623 const WCHAR *env;
624 const char *p1, *p2;
625 char *envUpper, *nameUpper;
626 Tcl_DString envString;
627
628 /*
629 * Convert the name to all upper case for the case insensitive comparison.
630 */
631
632 length = strlen(name);
633 nameUpper = (char *)ckalloc(length + 1);
634 memcpy(nameUpper, name, length+1);
635 Tcl_UtfToUpper(nameUpper);
636
637 Tcl_DStringInit(&envString);
638 for (i = 0, env = _wenviron[i]; env != NULL; i++, env = _wenviron[i]) {
639 /*
640 * Chop the env string off after the equal sign, then Convert the name
641 * to all upper case, so we do not have to convert all the characters
642 * after the equal sign.
643 */
644
645 envUpper = Tcl_WinTCharToUtf((TCHAR *)env, -1, &envString);
646 p1 = strchr(envUpper, '=');
647 if (p1 == NULL) {
648 continue;
649 }
650 length = (int) (p1 - envUpper);
651 Tcl_DStringSetLength(&envString, length+1);
652 Tcl_UtfToUpper(envUpper);
653
654 p1 = envUpper;
655 p2 = nameUpper;
656 for (; *p2 == *p1; p1++, p2++) {
657 /* NULL loop body. */
658 }
659 if ((*p1 == '=') && (*p2 == '\0')) {
660 *lengthPtr = length;
661 result = i;
662 goto done;
663 }
664
665 Tcl_DStringFree(&envString);
666 }
667
668 *lengthPtr = i;
669
670 done:
671 Tcl_DStringFree(&envString);
672 ckfree(nameUpper);
673 return result;
674 }
675
676 /*
677 * Local Variables:
678 * mode: c
679 * c-basic-offset: 4
680 * fill-column: 78
681 * End:
682 */