win32.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. // win32.cc - Helper functions for Microsoft-flavored OSs.
  2. /* Copyright (C) 2002, 2003, 2006 Free Software Foundation
  3. This file is part of libgcj.
  4. This software is copyrighted work licensed under the terms of the
  5. Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
  6. details. */
  7. #include <config.h>
  8. #include <platform.h>
  9. #include <sys/timeb.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <fcntl.h>
  13. #include <java-stack.h>
  14. #include <java/lang/ArithmeticException.h>
  15. #include <java/lang/UnsupportedOperationException.h>
  16. #include <java/io/IOException.h>
  17. #include <java/net/SocketException.h>
  18. #include <java/util/Properties.h>
  19. static LONG CALLBACK
  20. win32_exception_handler (LPEXCEPTION_POINTERS e)
  21. {
  22. if (e->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
  23. _Jv_ThrowNullPointerException();
  24. else if (e->ExceptionRecord->ExceptionCode == EXCEPTION_INT_DIVIDE_BY_ZERO)
  25. throw new java::lang::ArithmeticException;
  26. else
  27. return EXCEPTION_CONTINUE_SEARCH;
  28. }
  29. // Platform-specific executable name
  30. static char exec_name[MAX_PATH];
  31. // initialized in _Jv_platform_initialize()
  32. const char *_Jv_ThisExecutable (void)
  33. {
  34. return exec_name;
  35. }
  36. // Helper classes and methods implementation
  37. #ifdef MINGW_LIBGCJ_UNICODE
  38. // We're using the OS W (UNICODE) API, which means that we're speaking
  39. // the same language....
  40. jstring
  41. _Jv_Win32NewString (LPCTSTR pcsz)
  42. {
  43. return JvNewString ((jchar*) pcsz, _tcslen (pcsz));
  44. }
  45. #else
  46. // We're using the OS A functions, which means we need to translate between
  47. // UNICODE and the native character set.
  48. // First, let's set up some helper translation functions....
  49. // Converts the native string to any specified jstring, returning the
  50. // length of the jstring. If the specified jstring is null, we simply
  51. // compute and return the length.
  52. static int nativeToUnicode(LPCSTR pcsz, jstring jstr = 0)
  53. {
  54. jchar* buf = 0;
  55. int len = 0;
  56. if (jstr)
  57. {
  58. len = jstr->length();
  59. buf = JvGetStringChars(jstr);
  60. }
  61. return ::MultiByteToWideChar(GetACP(), 0, pcsz,
  62. strlen(pcsz), (LPWSTR) buf, len);
  63. }
  64. // Does the inverse of nativeToUnicode, with the same calling semantics.
  65. static int unicodeToNative(jstring jstr, LPSTR buf, int buflen)
  66. {
  67. return ::WideCharToMultiByte(GetACP(), 0, (LPWSTR) JvGetStringChars(jstr),
  68. jstr->length(), buf, buflen, NULL, NULL);
  69. }
  70. // Convenience function when the caller only wants to compute the length
  71. // of the native string.
  72. static int unicodeToNative(jstring jstr)
  73. {
  74. return unicodeToNative(jstr, 0, 0);
  75. }
  76. jstring
  77. _Jv_Win32NewString (LPCTSTR pcsz)
  78. {
  79. // Compute the length, allocate the jstring, then perform the conversion.
  80. int len = nativeToUnicode(pcsz);
  81. jstring jstr = JvAllocString(len);
  82. nativeToUnicode(pcsz, jstr);
  83. return jstr;
  84. }
  85. #endif // MINGW_LIBGCJ_UNICODE
  86. // class _Jv_Win32TempString
  87. _Jv_Win32TempString::_Jv_Win32TempString(jstring jstr):
  88. buf_(0)
  89. {
  90. if (jstr == 0)
  91. return;
  92. // We need space for the string length plus a null terminator.
  93. // Determine whether to use our stack-allocated buffer or a heap-
  94. // allocated one.
  95. #ifdef MINGW_LIBGCJ_UNICODE
  96. // A UNICODE character is a UNICODE character is a UNICODE character....
  97. int len = jstr->length();
  98. #else
  99. // Compute the length of the native character string.
  100. int len = unicodeToNative(jstr);
  101. #endif // MINGW_LIBGCJ_UNICODE
  102. int bytesNeeded = (len + 1) * sizeof(TCHAR);
  103. if (bytesNeeded <= (int) sizeof(stackbuf_))
  104. buf_ = stackbuf_;
  105. else
  106. buf_ = (LPTSTR) _Jv_Malloc(bytesNeeded);
  107. #ifdef MINGW_LIBGCJ_UNICODE
  108. // Copy the UNICODE characters to our buffer.
  109. _tcsncpy(buf_, (LPCTSTR) JvGetStringChars (jstr), len);
  110. #else
  111. // Convert the UNICODE string to a native one.
  112. unicodeToNative(jstr, buf_, len);
  113. #endif // MINGW_LIBGCJ_UNICODE
  114. buf_[len] = 0;
  115. }
  116. _Jv_Win32TempString::~_Jv_Win32TempString()
  117. {
  118. if (buf_ && buf_ != stackbuf_)
  119. _Jv_Free (buf_);
  120. }
  121. // class WSAEventWrapper
  122. WSAEventWrapper::WSAEventWrapper ():
  123. m_hEvent(0),
  124. m_fd(0),
  125. m_dwSelFlags(0)
  126. {}
  127. WSAEventWrapper::WSAEventWrapper (int fd, DWORD dwSelFlags):
  128. m_hEvent(0),
  129. m_fd(0),
  130. m_dwSelFlags(0)
  131. {
  132. init(fd, dwSelFlags);
  133. }
  134. void WSAEventWrapper::init(int fd, DWORD dwSelFlags)
  135. {
  136. m_fd = fd;
  137. m_dwSelFlags = dwSelFlags;
  138. m_hEvent = WSACreateEvent ();
  139. if (dwSelFlags)
  140. WSAEventSelect(fd, m_hEvent, dwSelFlags);
  141. }
  142. WSAEventWrapper::~WSAEventWrapper ()
  143. {
  144. if (m_dwSelFlags)
  145. {
  146. WSAEventSelect(m_fd, m_hEvent, 0);
  147. if (m_dwSelFlags & (FD_ACCEPT | FD_CONNECT))
  148. {
  149. // Set the socket back to non-blocking mode.
  150. // Ignore any error since we're in a destructor.
  151. unsigned long lSockOpt = 0L;
  152. // blocking mode
  153. ::ioctlsocket (m_fd, FIONBIO, &lSockOpt);
  154. }
  155. }
  156. WSACloseEvent (m_hEvent);
  157. }
  158. // Error string text.
  159. jstring
  160. _Jv_WinStrError (LPCTSTR lpszPrologue, int nErrorCode)
  161. {
  162. LPTSTR lpMsgBuf = 0;
  163. DWORD dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
  164. FORMAT_MESSAGE_FROM_SYSTEM |
  165. FORMAT_MESSAGE_IGNORE_INSERTS;
  166. FormatMessage (dwFlags,
  167. NULL,
  168. (DWORD) nErrorCode,
  169. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  170. (LPTSTR) &lpMsgBuf,
  171. 0,
  172. NULL);
  173. jstring ret;
  174. if (lpszPrologue)
  175. {
  176. LPTSTR lpszTemp =
  177. (LPTSTR) _Jv_Malloc ((_tcslen (lpszPrologue) +
  178. _tcslen (lpMsgBuf) + 3) * sizeof(TCHAR) );
  179. _tcscpy (lpszTemp, lpszPrologue);
  180. _tcscat (lpszTemp, _T(": "));
  181. _tcscat (lpszTemp, lpMsgBuf);
  182. ret = _Jv_Win32NewString (lpszTemp);
  183. _Jv_Free (lpszTemp);
  184. }
  185. else
  186. {
  187. ret = _Jv_Win32NewString (lpMsgBuf);
  188. }
  189. LocalFree(lpMsgBuf);
  190. return ret;
  191. }
  192. jstring
  193. _Jv_WinStrError (int nErrorCode)
  194. {
  195. return _Jv_WinStrError (0, nErrorCode);
  196. }
  197. void _Jv_ThrowIOException (DWORD dwErrorCode)
  198. {
  199. throw new java::io::IOException (_Jv_WinStrError (dwErrorCode));
  200. }
  201. void _Jv_ThrowIOException()
  202. {
  203. DWORD dwErrorCode = WSAGetLastError ();
  204. _Jv_ThrowIOException (dwErrorCode);
  205. }
  206. void _Jv_ThrowSocketException (DWORD dwErrorCode)
  207. {
  208. throw new java::net::SocketException (_Jv_WinStrError (dwErrorCode));
  209. }
  210. void _Jv_ThrowSocketException()
  211. {
  212. DWORD dwErrorCode = WSAGetLastError ();
  213. _Jv_ThrowSocketException (dwErrorCode);
  214. }
  215. // Platform-specific VM initialization.
  216. void
  217. _Jv_platform_initialize (void)
  218. {
  219. // Initialise winsock for networking
  220. WSADATA data;
  221. if (WSAStartup (MAKEWORD (2, 2), &data))
  222. MessageBox (NULL, _T("Error initialising winsock library."), _T("Error"),
  223. MB_OK | MB_ICONEXCLAMATION);
  224. // Install exception handler
  225. SetUnhandledExceptionFilter (win32_exception_handler);
  226. // Initialize our executable name.
  227. // FIXME: We unconditionally use the ANSI function because
  228. // _Jv_ThisExecutable returns a const char*. We should really
  229. // change _Jv_ThisExecutable to return a jstring.
  230. GetModuleFileNameA(NULL, exec_name, sizeof(exec_name));
  231. }
  232. // gettimeofday implementation.
  233. jlong
  234. _Jv_platform_gettimeofday ()
  235. {
  236. struct timeb t;
  237. ftime (&t);
  238. return t.time * 1000LL + t.millitm;
  239. }
  240. jlong
  241. _Jv_platform_nanotime ()
  242. {
  243. return _Jv_platform_gettimeofday () * 1000LL;
  244. }
  245. static bool dirExists (LPCTSTR dir)
  246. {
  247. DWORD dwAttrs = ::GetFileAttributes (dir);
  248. return dwAttrs != 0xFFFFFFFF &&
  249. (dwAttrs & FILE_ATTRIBUTE_DIRECTORY) != 0;
  250. }
  251. static void getUserHome(LPTSTR userHome, LPCTSTR userId)
  252. {
  253. LPTSTR uh = _tgetenv (_T("USERPROFILE"));
  254. if (uh)
  255. {
  256. _tcscpy(userHome, uh);
  257. }
  258. else
  259. {
  260. // Make a half-hearted attempt to support this
  261. // legacy version of Windows. Try %WINDIR%\Profiles\%USERNAME%
  262. // and failing this, use %WINDIR%.
  263. //
  264. // See:http://java.sun.com/docs/books/tutorial/security1.2/summary/files.html#UserPolicy
  265. //
  266. // To do this correctly, we'd have to factor in the
  267. // Windows version, but if we did that, then this attempt
  268. // wouldn't be half-hearted.
  269. TCHAR userHomePath[MAX_PATH], winHome[MAX_PATH];
  270. ::GetWindowsDirectory(winHome, MAX_PATH);
  271. // assume this call always succeeds
  272. _stprintf(userHomePath, _T("%s\\Profiles\\%s"), winHome, userId);
  273. if (dirExists (userHomePath))
  274. _tcscpy(userHome, userHomePath);
  275. else
  276. _tcscpy(userHome, winHome);
  277. }
  278. }
  279. // Set platform-specific System properties.
  280. void
  281. _Jv_platform_initProperties (java::util::Properties* newprops)
  282. {
  283. // A convenience define.
  284. #define SET(Prop,Val) \
  285. newprops->put(JvNewStringLatin1 (Prop), _Jv_Win32NewString (Val))
  286. SET ("file.separator", _T("\\"));
  287. SET ("path.separator", _T(";"));
  288. SET ("line.separator", _T("\r\n"));
  289. // Use GetCurrentDirectory to set 'user.dir'.
  290. DWORD buflen = MAX_PATH;
  291. TCHAR buffer[buflen];
  292. if (buffer != NULL)
  293. {
  294. if (GetCurrentDirectory (buflen, buffer))
  295. SET ("user.dir", buffer);
  296. if (GetTempPath (buflen, buffer))
  297. SET ("java.io.tmpdir", buffer);
  298. }
  299. // Use GetUserName to set 'user.name'.
  300. buflen = 257; // UNLEN + 1
  301. TCHAR userName[buflen];
  302. if (GetUserName (userName, &buflen))
  303. SET ("user.name", userName);
  304. // Set user.home
  305. TCHAR userHome[MAX_PATH];
  306. getUserHome(userHome, userName);
  307. SET ("user.home", userHome);
  308. // Get and set some OS info.
  309. OSVERSIONINFO osvi;
  310. ZeroMemory (&osvi, sizeof(OSVERSIONINFO));
  311. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  312. if (GetVersionEx (&osvi))
  313. {
  314. if (buffer != NULL)
  315. {
  316. _stprintf (buffer, _T("%d.%d"), (int) osvi.dwMajorVersion,
  317. (int) osvi.dwMinorVersion);
  318. SET ("os.version", buffer);
  319. }
  320. switch (osvi.dwPlatformId)
  321. {
  322. case VER_PLATFORM_WIN32_WINDOWS:
  323. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
  324. SET ("os.name", _T("Windows 95"));
  325. else if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
  326. SET ("os.name", _T("Windows 98"));
  327. else if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
  328. SET ("os.name", _T("Windows Me"));
  329. else
  330. SET ("os.name", _T("Windows ??"));
  331. break;
  332. case VER_PLATFORM_WIN32_NT:
  333. if (osvi.dwMajorVersion <= 4 )
  334. SET ("os.name", _T("Windows NT"));
  335. else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  336. SET ("os.name", _T("Windows 2000"));
  337. else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  338. SET ("os.name", _T("Windows XP"));
  339. else
  340. SET ("os.name", _T("Windows NT ??"));
  341. break;
  342. default:
  343. SET ("os.name", _T("Windows UNKNOWN"));
  344. break;
  345. }
  346. }
  347. // Set the OS architecture.
  348. SYSTEM_INFO si;
  349. GetSystemInfo (&si);
  350. switch (si.wProcessorArchitecture)
  351. {
  352. case PROCESSOR_ARCHITECTURE_INTEL:
  353. SET ("os.arch", _T("x86"));
  354. break;
  355. case PROCESSOR_ARCHITECTURE_MIPS:
  356. SET ("os.arch", _T("mips"));
  357. break;
  358. case PROCESSOR_ARCHITECTURE_ALPHA:
  359. SET ("os.arch", _T("alpha"));
  360. break;
  361. case PROCESSOR_ARCHITECTURE_PPC:
  362. SET ("os.arch", _T("ppc"));
  363. break;
  364. case PROCESSOR_ARCHITECTURE_IA64:
  365. SET ("os.arch", _T("ia64"));
  366. break;
  367. case PROCESSOR_ARCHITECTURE_UNKNOWN:
  368. default:
  369. SET ("os.arch", _T("unknown"));
  370. break;
  371. }
  372. }
  373. int
  374. _Jv_pipe (int filedes[2])
  375. {
  376. return _pipe (filedes, 4096, _O_BINARY);
  377. }
  378. void
  379. _Jv_platform_close_on_exec (HANDLE h)
  380. {
  381. // Mark the handle as non-inheritable. This has
  382. // no effect under Win9X.
  383. SetHandleInformation (h, HANDLE_FLAG_INHERIT, 0);
  384. }
  385. // Given an address, find the object that defines it and the nearest
  386. // defined symbol to that address. Returns 0 if no object defines this
  387. // address.
  388. int
  389. _Jv_platform_dladdr (void *addr, _Jv_AddrInfo *info)
  390. {
  391. // Since we do not have dladdr() on Windows, we use a trick involving
  392. // VirtualQuery() to find the module (EXE or DLL) that contains a given
  393. // address. This was taken from Matt Pietrek's "Under the Hood" column
  394. // for the April 1997 issue of Microsoft Systems Journal.
  395. MEMORY_BASIC_INFORMATION mbi;
  396. if (!VirtualQuery (addr, &mbi, sizeof (mbi)))
  397. {
  398. return 0;
  399. }
  400. HMODULE hMod = (HMODULE) mbi.AllocationBase;
  401. char moduleName[MAX_PATH];
  402. // FIXME: We explicitly use the ANSI variant of the function here.
  403. if (!GetModuleFileNameA (hMod, moduleName, sizeof (moduleName)))
  404. {
  405. return 0;
  406. }
  407. char *file_name = (char *)(malloc (strlen (moduleName) + 1));
  408. strcpy (file_name, moduleName);
  409. info->file_name = file_name;
  410. // FIXME.
  411. info->base = NULL;
  412. info->sym_name = NULL;
  413. info->sym_addr = NULL;
  414. return 1;
  415. }