ntlib.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /* Utility and Unix shadow routines for GNU Emacs support programs on NT.
  2. Copyright (C) 1994, 2001-2015 Free Software Foundation, Inc.
  3. Author: Geoff Voelker (voelker@cs.washington.edu)
  4. Created: 10-8-94
  5. This file is part of GNU Emacs.
  6. GNU Emacs is free software: you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation, either version 3 of the License, or
  9. (at your option) any later version.
  10. GNU Emacs is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
  16. #include <windows.h>
  17. #include <stdlib.h>
  18. #include <stdio.h>
  19. #include <time.h>
  20. #include <direct.h>
  21. #include <sys/types.h>
  22. #include <sys/stat.h>
  23. #include <errno.h>
  24. #include <ctype.h>
  25. #include <sys/timeb.h>
  26. #include <mbstring.h>
  27. #include "ntlib.h"
  28. /* MinGW64 defines _TIMEZONE_DEFINED and defines 'struct timespec' in
  29. its system headers. */
  30. #ifndef _TIMEZONE_DEFINED
  31. struct timezone
  32. {
  33. int tz_minuteswest; /* minutes west of Greenwich */
  34. int tz_dsttime; /* type of dst correction */
  35. };
  36. #endif
  37. #define MAXPATHLEN _MAX_PATH
  38. /* Emulate sleep...we could have done this with a define, but that
  39. would necessitate including windows.h in the files that used it.
  40. This is much easier. */
  41. unsigned
  42. sleep (unsigned seconds)
  43. {
  44. Sleep (seconds * 1000);
  45. return 0;
  46. }
  47. /* Get the current working directory. */
  48. char *
  49. getwd (char *dir)
  50. {
  51. if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
  52. return dir;
  53. return NULL;
  54. }
  55. static HANDLE getppid_parent;
  56. static int getppid_ppid;
  57. int
  58. getppid (void)
  59. {
  60. char *ppid;
  61. DWORD result;
  62. ppid = getenv ("EM_PARENT_PROCESS_ID");
  63. if (!ppid)
  64. {
  65. printf ("no pid.\n");
  66. return 0;
  67. }
  68. else
  69. {
  70. getppid_ppid = atoi (ppid);
  71. }
  72. if (!getppid_parent)
  73. {
  74. getppid_parent = OpenProcess (SYNCHRONIZE, FALSE, atoi (ppid));
  75. if (!getppid_parent)
  76. {
  77. printf ("Failed to open handle to parent process: %d\n",
  78. GetLastError ());
  79. exit (1);
  80. }
  81. }
  82. result = WaitForSingleObject (getppid_parent, 0);
  83. switch (result)
  84. {
  85. case WAIT_TIMEOUT:
  86. /* The parent is still alive. */
  87. return getppid_ppid;
  88. case WAIT_OBJECT_0:
  89. /* The parent is gone. Return the pid of Unix init (1). */
  90. return 1;
  91. case WAIT_FAILED:
  92. default:
  93. printf ("Checking parent status failed: %d\n", GetLastError ());
  94. exit (1);
  95. }
  96. }
  97. char *
  98. getlogin (void)
  99. {
  100. static char user_name[256];
  101. DWORD length = sizeof (user_name);
  102. if (GetUserName (user_name, &length))
  103. return user_name;
  104. return NULL;
  105. }
  106. char *
  107. cuserid (char * s)
  108. {
  109. char * name = getlogin ();
  110. if (s)
  111. return strcpy (s, name ? name : "");
  112. return name;
  113. }
  114. unsigned
  115. getuid (void)
  116. {
  117. return 0;
  118. }
  119. unsigned
  120. geteuid (void)
  121. {
  122. return getuid ();
  123. }
  124. unsigned
  125. getgid (void)
  126. {
  127. return 0;
  128. }
  129. unsigned
  130. getegid (void)
  131. {
  132. return 0;
  133. }
  134. int
  135. setuid (unsigned uid)
  136. {
  137. return 0;
  138. }
  139. int
  140. setregid (unsigned rgid, unsigned gid)
  141. {
  142. return 0;
  143. }
  144. struct passwd *
  145. getpwuid (unsigned uid)
  146. {
  147. return NULL;
  148. }
  149. char *
  150. getpass (const char * prompt)
  151. {
  152. static char input[256];
  153. HANDLE in;
  154. HANDLE err;
  155. DWORD count;
  156. in = GetStdHandle (STD_INPUT_HANDLE);
  157. err = GetStdHandle (STD_ERROR_HANDLE);
  158. if (in == INVALID_HANDLE_VALUE || err == INVALID_HANDLE_VALUE)
  159. return NULL;
  160. if (WriteFile (err, prompt, strlen (prompt), &count, NULL))
  161. {
  162. int istty = (GetFileType (in) == FILE_TYPE_CHAR);
  163. DWORD old_flags;
  164. int rc;
  165. if (istty)
  166. {
  167. if (GetConsoleMode (in, &old_flags))
  168. SetConsoleMode (in, ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT);
  169. else
  170. istty = 0;
  171. }
  172. rc = ReadFile (in, input, sizeof (input), &count, NULL);
  173. if (count >= 2 && input[count - 2] == '\r')
  174. input[count - 2] = '\0';
  175. else
  176. {
  177. char buf[256];
  178. while (ReadFile (in, buf, sizeof (buf), &count, NULL) > 0)
  179. if (count >= 2 && buf[count - 2] == '\r')
  180. break;
  181. }
  182. WriteFile (err, "\r\n", 2, &count, NULL);
  183. if (istty)
  184. SetConsoleMode (in, old_flags);
  185. if (rc)
  186. return input;
  187. }
  188. return NULL;
  189. }
  190. /* This is needed because lib/gettime.c calls gettimeofday, which MSVC
  191. doesn't have. Copied from w32.c. */
  192. void
  193. gettimeofday (struct timeval *tv, struct timezone *tz)
  194. {
  195. struct _timeb tb;
  196. _ftime (&tb);
  197. tv->tv_sec = tb.time;
  198. tv->tv_usec = tb.millitm * 1000L;
  199. /* Implementation note: _ftime sometimes doesn't update the dstflag
  200. according to the new timezone when the system timezone is
  201. changed. We could fix that by using GetSystemTime and
  202. GetTimeZoneInformation, but that doesn't seem necessary, since
  203. Emacs always calls gettimeofday with the 2nd argument NULL (see
  204. current_emacs_time). */
  205. if (tz)
  206. {
  207. tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
  208. tz->tz_dsttime = tb.dstflag; /* type of dst correction */
  209. }
  210. }
  211. int
  212. fchown (int fd, unsigned uid, unsigned gid)
  213. {
  214. return 0;
  215. }
  216. /* Place a wrapper around the MSVC version of ctime. It returns NULL
  217. on network directories, so we handle that case here.
  218. (Ulrich Leodolter, 1/11/95). */
  219. char *
  220. sys_ctime (const time_t *t)
  221. {
  222. char *str = (char *) ctime (t);
  223. return (str ? str : "Sun Jan 01 00:00:00 1970");
  224. }
  225. FILE *
  226. sys_fopen (const char * path, const char * mode)
  227. {
  228. return fopen (path, mode);
  229. }
  230. int
  231. sys_chdir (const char * path)
  232. {
  233. return _chdir (path);
  234. }
  235. static FILETIME utc_base_ft;
  236. static long double utc_base;
  237. static int init = 0;
  238. static time_t
  239. convert_time (FILETIME ft)
  240. {
  241. long double ret;
  242. if (CompareFileTime (&ft, &utc_base_ft) < 0)
  243. return 0;
  244. ret = (long double) ft.dwHighDateTime
  245. * 4096.0L * 1024.0L * 1024.0L + ft.dwLowDateTime;
  246. ret -= utc_base;
  247. return (time_t) (ret * 1e-7L);
  248. }
  249. static int
  250. is_exec (const char * name)
  251. {
  252. char * p = strrchr (name, '.');
  253. return
  254. (p != NULL
  255. && (stricmp (p, ".exe") == 0 ||
  256. stricmp (p, ".com") == 0 ||
  257. stricmp (p, ".bat") == 0 ||
  258. stricmp (p, ".cmd") == 0));
  259. }
  260. /* FIXME? This is in config.nt now - is this still needed? */
  261. #define IS_DIRECTORY_SEP(x) ((x) == '/' || (x) == '\\')
  262. /* We need this because nt/inc/sys/stat.h defines struct stat that is
  263. incompatible with the MS run-time libraries. */
  264. int
  265. stat (const char * path, struct stat * buf)
  266. {
  267. WIN32_FIND_DATA wfd;
  268. HANDLE fh;
  269. int permission;
  270. int len;
  271. int rootdir = FALSE;
  272. char *name = alloca (FILENAME_MAX);
  273. if (!init)
  274. {
  275. /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
  276. SYSTEMTIME st;
  277. st.wYear = 1970;
  278. st.wMonth = 1;
  279. st.wDay = 1;
  280. st.wHour = 0;
  281. st.wMinute = 0;
  282. st.wSecond = 0;
  283. st.wMilliseconds = 0;
  284. SystemTimeToFileTime (&st, &utc_base_ft);
  285. utc_base = (long double) utc_base_ft.dwHighDateTime
  286. * 4096.0L * 1024.0L * 1024.0L + utc_base_ft.dwLowDateTime;
  287. init = 1;
  288. }
  289. if (path == NULL || buf == NULL || *path == '\0')
  290. {
  291. errno = EFAULT;
  292. return -1;
  293. }
  294. if (_mbspbrk (path, "*?|<>\""))
  295. {
  296. errno = ENOENT;
  297. return -1;
  298. }
  299. strcpy (name, path);
  300. /* Remove trailing directory separator, unless name is the root
  301. directory of a drive in which case ensure there is a trailing
  302. separator. */
  303. len = strlen (name);
  304. rootdir = IS_DIRECTORY_SEP (name[0])
  305. || (len == 3 && name[1] == ':' && IS_DIRECTORY_SEP (name[2]));
  306. if (rootdir)
  307. {
  308. if (GetDriveType (name) < 2)
  309. {
  310. errno = ENOENT;
  311. return -1;
  312. }
  313. memset (&wfd, 0, sizeof (wfd));
  314. wfd.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
  315. wfd.ftCreationTime = utc_base_ft;
  316. wfd.ftLastAccessTime = utc_base_ft;
  317. wfd.ftLastWriteTime = utc_base_ft;
  318. strcpy (wfd.cFileName, name);
  319. }
  320. else
  321. {
  322. if (IS_DIRECTORY_SEP (name[len-1]))
  323. name[len - 1] = 0;
  324. fh = FindFirstFile (name, &wfd);
  325. if (fh == INVALID_HANDLE_VALUE)
  326. {
  327. errno = ENOENT;
  328. return -1;
  329. }
  330. FindClose (fh);
  331. }
  332. buf->st_mode = (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ?
  333. S_IFDIR : S_IFREG;
  334. buf->st_nlink = 1;
  335. buf->st_ino = 0;
  336. if (name[0] && name[1] == ':')
  337. buf->st_dev = tolower (name[0]) - 'a' + 1;
  338. else
  339. buf->st_dev = _getdrive ();
  340. buf->st_rdev = buf->st_dev;
  341. buf->st_size = wfd.nFileSizeLow;
  342. /* Convert timestamps to Unix format. */
  343. buf->st_mtime = convert_time (wfd.ftLastWriteTime);
  344. buf->st_atime = convert_time (wfd.ftLastAccessTime);
  345. if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
  346. buf->st_ctime = convert_time (wfd.ftCreationTime);
  347. if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
  348. /* determine rwx permissions */
  349. if (wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
  350. permission = S_IREAD;
  351. else
  352. permission = S_IREAD | S_IWRITE;
  353. if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  354. permission |= S_IEXEC;
  355. else if (is_exec (name))
  356. permission |= S_IEXEC;
  357. buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
  358. return 0;
  359. }
  360. int
  361. lstat (const char * path, struct stat * buf)
  362. {
  363. return stat (path, buf);
  364. }
  365. /* Implementation of mkostemp for MS-Windows, to avoid race conditions
  366. when using mktemp. Copied from w32.c.
  367. This is used only in update-game-score.c. It is overkill for that
  368. use case, since update-game-score renames the temporary file into
  369. the game score file, which isn't atomic on MS-Windows anyway, when
  370. the game score already existed before running the program, which it
  371. almost always does. But using a simpler implementation just to
  372. make a point is uneconomical... */
  373. int
  374. mkostemp (char * template, int flags)
  375. {
  376. char * p;
  377. int i, fd = -1;
  378. unsigned uid = GetCurrentThreadId ();
  379. int save_errno = errno;
  380. static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
  381. errno = EINVAL;
  382. if (template == NULL)
  383. return -1;
  384. p = template + strlen (template);
  385. i = 5;
  386. /* replace up to the last 5 X's with uid in decimal */
  387. while (--p >= template && p[0] == 'X' && --i >= 0)
  388. {
  389. p[0] = '0' + uid % 10;
  390. uid /= 10;
  391. }
  392. if (i < 0 && p[0] == 'X')
  393. {
  394. i = 0;
  395. do
  396. {
  397. p[0] = first_char[i];
  398. if ((fd = open (template,
  399. flags | _O_CREAT | _O_EXCL | _O_RDWR,
  400. S_IRUSR | S_IWUSR)) >= 0
  401. || errno != EEXIST)
  402. {
  403. if (fd >= 0)
  404. errno = save_errno;
  405. return fd;
  406. }
  407. }
  408. while (++i < sizeof (first_char));
  409. }
  410. /* Template is badly formed or else we can't generate a unique name. */
  411. return -1;
  412. }
  413. /* On Windows, you cannot rename into an existing file. */
  414. int
  415. sys_rename (const char *from, const char *to)
  416. {
  417. int retval = rename (from, to);
  418. if (retval < 0 && errno == EEXIST)
  419. {
  420. if (unlink (to) == 0)
  421. retval = rename (from, to);
  422. }
  423. return retval;
  424. }