2 Copyright (C) 2009 John Emmas
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 extern "C" WINBASEAPI BOOL WINAPI
25 CreateHardLinkA( LPCSTR lpFileName,
26 LPCSTR lpExistingFileName,
27 LPSECURITY_ATTRIBUTES lpSecurityAttributes ); // Needs kernel32.lib on anything higher than Win2K
36 #include <pbd/error.h>
37 #include <ardourext/misc.h>
38 #include <ardourext/pthread.h> // Should ensure that we include the right
39 // version - but we'll check anyway, later
43 #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
47 int tz_minuteswest; /* minutes W of Greenwich */
48 int tz_dsttime; /* type of dst correction */
51 PBD_API int PBD_APICALLTYPE
52 gettimeofday(struct timeval *__restrict tv, __timezone_ptr_t tz) // Does this need to be exported ?
55 unsigned __int64 tmpres = 0;
56 static int tzflag = 0;
60 GetSystemTimeAsFileTime(&ft);
62 tmpres |= ft.dwHighDateTime;
64 tmpres |= ft.dwLowDateTime;
66 /*converting file time to unix epoch*/
67 tmpres /= 10; /*convert into microseconds*/
68 tmpres -= DELTA_EPOCH_IN_MICROSECS;
69 tv->tv_sec = (long)(tmpres / 1000000UL);
70 tv->tv_usec = (long)(tmpres % 1000000UL);
75 struct timezone *ptz = static_cast<struct timezone*> (tz);
83 ptz->tz_minuteswest = _timezone / 60;
84 ptz->tz_dsttime = _daylight;
91 // Define the default comparison operators for Windows (ptw32) 'pthread_t' (not used
92 // by Ardour AFAIK but would be needed if an array of 'pthread_t' had to be sorted).
93 #ifndef PTHREAD_H // Defined by PTW32 (Linux and other versions define _PTHREAD_H)
94 #error "An incompatible version of 'pthread.h' is #included. Use only the Windows (ptw32) version!"
96 bool operator> (const pthread_t& lhs, const pthread_t& rhs)
98 return (std::greater<void*>()(lhs.p, rhs.p));
101 bool operator< (const pthread_t& lhs, const pthread_t& rhs)
103 return (std::less<void*>()(lhs.p, rhs.p));
106 bool operator!= (const pthread_t& lhs, const pthread_t& rhs)
108 return (std::not_equal_to<void*>()(lhs.p, rhs.p));
111 bool operator== (const pthread_t& lhs, const pthread_t& rhs)
113 return (!(lhs != rhs));
117 // Functions supplied (later) to std::transform
118 //***************************************************************
120 // invert_backslash()
122 // Examines a supplied ASCII character and (if the character is
123 // a backslash) converts it to a forward slash,
127 // The supplied character (converted, if it was a backslash)
129 char invert_backslash(char character)
131 if ('\\' == character)
137 //***************************************************************
139 // invert_forwardslash()
141 // Examines a supplied ASCII character and (if the character is
142 // a forward slash) converts it to a backslash,
146 // The supplied character (converted, if it was a fwd slash)
148 char invert_forwardslash(char character)
150 if ('/' == character)
157 //***************************************************************
161 // Emulates pread() using _lseek()/_read()/_lseek().
165 // On Success: The number of bytes read from the file
168 PBD_API ssize_t PBD_APICALLTYPE
169 pread(int handle, void *buf, size_t nbytes, off_t offset)
174 off_t old_offset = _tell(handle);
180 _lseek(handle, offset, SEEK_SET);
181 ret = _read(handle, buf, nbytes);
184 _lseek(handle, old_offset, SEEK_SET);
192 //***************************************************************
196 // Emulates pwrite() using _lseek()/_write()/_lseek().
200 // On Success: The number of bytes written to the file
203 PBD_API ssize_t PBD_APICALLTYPE
204 pwrite(int handle, const void *buf, size_t nbytes, off_t offset)
209 off_t old_offset = _lseek(handle, offset, SEEK_SET);
215 ret = _write(handle, buf, nbytes);
218 _lseek(handle, old_offset, SEEK_SET);
227 //***************************************************************
229 // TestForMinimumSpecOS()
231 // Tests the user's OS to see if it is Win2K or later (could be
232 // expanded quite easily to accommodate other OS's)
236 // On Success: TRUE (if the user's OS matches the minimum spec)
237 // On Failure: FALSE otherwise
239 PBD_API bool PBD_APICALLTYPE
240 TestForMinimumSpecOS(char *revision /* currently ignored */)
243 #ifdef PLATFORM_WINDOWS
245 HINSTANCE hKernelDll = (HINSTANCE)dlopen("kernel32.dll", RTLD_NOW);
249 // 'CreateHardLink()' is only available from Win2K onwards.
250 if (NULL != dlsym(hKernelDll, "CreateHardLinkA"))
256 // Other OS's could be accommodated here
262 //***************************************************************
266 // Emulates POSIX realpath() using Win32 _fullpath().
270 // On Success: A pointer to the resolved (absolute) path
273 PBD_API char* PBD_APICALLTYPE
274 realpath (const char *original_path, char resolved_path[_MAX_PATH+1])
277 bool bIsSymLink = 0; // We'll probably need to test the incoming path
278 // to find out if it points to a Windows shortcut
279 // (or a hard link) and set this appropriately.
282 // At the moment I'm not sure if Windows '_fullpath()' is directly
283 // equivalent to POSIX 'realpath()' - in as much as the latter will
284 // resolve the supplied path if it happens to point to a symbolic
285 // link ('_fullpath()' probably DOESN'T do this but I'm not really
286 // sure if Ardour needs such functionality anyway). Therefore we'll
287 // possibly need to add that functionality here at a later date.
291 char temp[(MAX_PATH+1)*6]; // Allow for maximum length of a path in UTF8 characters
293 // POSIX 'realpath()' requires that the buffer size is at
294 // least PATH_MAX+1, so assume that the user knew this !!
295 pRet = _fullpath(temp, Glib::locale_from_utf8(original_path).c_str(), _MAX_PATH);
297 strcpy(resolved_path, Glib::locale_to_utf8(temp).c_str());
304 //***************************************************************
308 // Creates a pointer to a DIR structure, appropriately filled in
309 // and ready to begin a directory search iteration.
313 // On Success: Pointer to a (heap based) DIR structure
316 PBD_API DIR* PBD_APICALLTYPE
317 opendir (const char *szPath)
319 wchar_t wpath[PATH_MAX+1];
328 if ((!errno) && ('\0' == szPath[0]))
331 // Determine if the given path really is a directory
334 if (0 == MultiByteToWideChar (CP_UTF8, 0, (LPCSTR)szPath, -1, (LPWSTR)wpath, sizeof(wpath)))
337 if ((!errno) && ((rc = GetFileAttributesW(wpath)) == -1))
340 if ((!errno) && (!(rc & FILE_ATTRIBUTE_DIRECTORY)))
341 // Error. Entry exists but not a directory. */
346 // Allocate enough memory to store DIR structure, plus
347 // the complete directory path originally supplied.
348 pDir = (DIR *)malloc(sizeof(DIR) + strlen(szPath) + strlen("\\") + strlen ("*"));
352 // Error - out of memory
359 // Create the search expression
360 strcpy(pDir->dd_name, szPath);
362 // Add a backslash if the path doesn't already end with one
363 if (pDir->dd_name[0] != '\0' &&
364 pDir->dd_name[strlen(pDir->dd_name) - 1] != '/' &&
365 pDir->dd_name[strlen(pDir->dd_name) - 1] != '\\')
367 strcat (pDir->dd_name, "\\");
370 // Add the search pattern
371 strcat(pDir->dd_name, "*");
373 // Initialize handle to -1 so that a premature closedir()
374 // doesn't try to call _findclose() on it.
375 pDir->dd_handle = (-1);
377 // Initialize the status
380 // Initialize the dirent structure. 'ino' and 'reclen' are invalid under Win32
381 // and 'name' simply points at the appropriate part of the findfirst_t struct.
382 pDir->dd_dir.d_ino = 0;
383 pDir->dd_dir.d_reclen = 0;
384 pDir->dd_dir.d_namlen = 0;
385 strcpy(pDir->dd_dir.d_name, pDir->dd_dta.name);
387 return (pDir); // Succeeded
392 return (DIR *) 0; // Failed
396 //***************************************************************
400 // Return a pointer to a dirent struct, filled with information
401 // about the next entry in the directory.
405 // On Success: A pointer to the supplied DIR's 'dirent' struct
408 PBD_API struct dirent* PBD_APICALLTYPE
414 // Check for valid DIR struct
418 if ((strcmp(pDir->dd_dir.d_name, pDir->dd_dta.name)) && (!errno))
419 // The structure does not seem to be set up correctly
423 if (pDir->dd_stat < 0)
425 // We have already returned all files in this directory
426 // (or the structure has an invalid dd_stat).
427 return (struct dirent *)0;
429 else if (pDir->dd_stat == 0)
431 // We haven't started the search yet.
433 pDir->dd_handle = _findfirst (Glib::locale_from_utf8(pDir->dd_name).c_str(), &(pDir->dd_dta));
435 if (pDir->dd_handle == -1)
436 // The directory is empty
443 // Do not return ENOENT on last file in directory
446 // Get the next search entry
447 if (_findnext (pDir->dd_handle, &(pDir->dd_dta)))
449 // We are off the end or otherwise error
451 _findclose (pDir->dd_handle);
452 pDir->dd_handle = -1;
456 // Update to indicate the correct status number
460 if (pDir->dd_stat > 0)
462 // We successfully got an entry. Details about the file are
463 // already appropriately filled in except for the length of
465 strcpy(pDir->dd_dir.d_name, pDir->dd_dta.name);
466 pDir->dd_dir.d_namlen = strlen (pDir->dd_dir.d_name);
467 return (&pDir->dd_dir); // Succeeded
471 return (struct dirent *) 0; // Failed
475 //***************************************************************
479 // Frees the resources allocated by opendir().
486 PBD_API int PBD_APICALLTYPE
497 if ((-1) != pDir->dd_handle)
498 rc = _findclose (pDir->dd_handle);
500 // Free the DIR structure
503 return rc; // Succeeded
506 return (-1); // Failed
509 //***************************************************************
513 // Emulates Linux mkstemp() using Win32 _mktemp() and _open() etc.
517 // On Success: A file descriptor for the opened file.
520 PBD_API int PBD_APICALLTYPE
521 mkstemp (char *template_name)
525 char szTempPath[PATH_MAX+100]; // Just ensure we have plenty of buffer space
527 if (NULL != (szFileName = _mktemp(template_name)))
529 if (0 != ::GetTempPathA(sizeof(szTempPath), szTempPath))
531 strcat(szTempPath, szFileName);
532 ret = _open(szTempPath, (_O_CREAT|_O_BINARY|_O_TEMPORARY|_O_RDWR|_O_TRUNC), _S_IWRITE);
540 //***************************************************************
544 // Emulates Linux link() using Win32 CreateHardLink()(NTFS only).
548 // On Success: Non-zero.
549 // On Failure: Zero (call 'GetLastError()' to retrieve info)
551 PBD_API int PBD_APICALLTYPE
552 ntfs_link (const char *existing_filepath, const char *link_filepath)
554 int ret = 1; // 'ERROR_INVALID_FUNCTION'
555 bool bValidPath = false;
557 // Make sure we've been sent a valid input string
558 if (existing_filepath && link_filepath)
560 std::string strRoot = existing_filepath;
562 if ((1 < strRoot.length()) && ('\\' == existing_filepath[0]) && ('\\' == existing_filepath[1]))
566 // We've been sent a network path. Convert backslashes to forward slashes temporarily.
567 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
569 // Now, if there are less than four slashes, add a fourth one or abort
570 std::string::iterator iter = strRoot.begin();
571 while ((slashcnt < 4) && (iter != strRoot.end()))
581 // If only 3 slashes were counted, add a trailing slash
585 // Now find the position of the fourth slash
586 iter = strRoot.begin();
588 for (slashcnt=0; slashcnt<4;)
595 if (++iter == strRoot.end())
599 strRoot.resize(charcnt);
605 // Assume a standard Windows style path
606 if (1 < strRoot.length() && (':' == existing_filepath[1]))
608 // Convert backslashes to forward slashes temporarily.
609 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
611 if (2 == strRoot.length())
614 if ('/' == strRoot[2])
624 char szFileSystemType[_MAX_PATH+1];
626 // Restore the original backslashes
627 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_forwardslash);
629 // Windows only supports hard links for the NTFS filing
630 // system, so let's make sure that's what we're using!!
631 if (::GetVolumeInformationA(strRoot.c_str(), NULL, 0, NULL, NULL, NULL, szFileSystemType, _MAX_PATH+1))
633 std::string strRootFileSystemType = szFileSystemType;
634 std::transform(strRootFileSystemType.begin(), strRootFileSystemType.end(), strRootFileSystemType.begin(), ::toupper);
635 #if (_WIN32_WINNT >= 0x0500)
636 if (0 == strRootFileSystemType.compare("NTFS"))
638 if (TestForMinimumSpecOS()) // Hard links were only available from Win2K onwards
639 if (0 == CreateHardLinkA(link_filepath, existing_filepath, NULL))
640 { // Note that the above API call cannot create a link to a directory, so
641 // should we also be checking that the supplied path was actually a file?
642 ret = GetLastError();
645 SetLastError(ret = 0); // 'NO_ERROR'
649 ret = 4300; // 'ERROR_INVALID_MEDIA'
655 ret = 123; // 'ERROR_INVALID_NAME'
658 ret = 161; // 'ERROR_BAD_PATHNAME'
670 //***************************************************************
674 // Emulates Linux unlink() using Win32 DeleteFile()(NTFS only).
678 // On Success: Non-zero.
679 // On Failure: Zero (call 'GetLastError()' to retrieve info)
681 PBD_API int PBD_APICALLTYPE
682 ntfs_unlink (const char *link_filepath)
684 int ret = 1; // 'ERROR_INVALID_FUNCTION'
685 bool bValidPath = false;
687 // Make sure we've been sent a valid input string
690 std::string strRoot = link_filepath;
692 if ((1 < strRoot.length()) && ('\\' == link_filepath[0]) && ('\\' == link_filepath[1]))
696 // We've been sent a network path. Convert backslashes to forward slashes temporarily.
697 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
699 // Now, if there are less than four slashes, add a fourth one or abort
700 std::string::iterator iter = strRoot.begin();
701 while ((slashcnt < 4) && (iter != strRoot.end()))
711 // If only 3 slashes were counted, add a trailing slash
715 // Now find the position of the fourth slash
716 iter = strRoot.begin();
718 for (slashcnt=0; slashcnt<4;)
725 if (++iter == strRoot.end())
729 strRoot.resize(charcnt);
735 // Assume a standard Windows style path
736 if (1 < strRoot.length() && (':' == link_filepath[1]))
738 // Convert backslashes to forward slashes temporarily.
739 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
741 if (2 == strRoot.length())
744 if ('/' == strRoot[2])
754 char szFileSystemType[_MAX_PATH+1];
756 // Restore the original backslashes
757 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_forwardslash);
759 // Windows only supports hard links for the NTFS filing
760 // system, so let's make sure that's what we're using!!
761 if (::GetVolumeInformationA(strRoot.c_str(), NULL, 0, NULL, NULL, NULL, szFileSystemType, _MAX_PATH+1))
763 std::string strRootFileSystemType = szFileSystemType;
764 std::transform(strRootFileSystemType.begin(), strRootFileSystemType.end(), strRootFileSystemType.begin(), ::toupper);
765 #if (_WIN32_WINNT >= 0x0500)
766 if (0 == strRootFileSystemType.compare("NTFS"))
767 if (TestForMinimumSpecOS()) // Hard links were only available from Win2K onwards
768 if (0 == DeleteFileA(link_filepath))
769 ret = GetLastError();
771 ret = 0; // 'NO_ERROR'
776 ret = 123; // 'ERROR_INVALID_NAME'
779 ret = 161; // 'ERROR_BAD_PATHNAME'
793 //***************************************************************
797 // Emulates POSIX dlopen() using Win32 LoadLibrary().
801 // On Success: A handle to the opened DLL
804 PBD_API void* PBD_APICALLTYPE
805 dlopen (const char *file_name, int mode)
807 // Note that 'mode' is ignored in Win32
808 return(::LoadLibraryA(Glib::locale_from_utf8(file_name).c_str()));
812 //***************************************************************
816 // Emulates POSIX dlclose() using Win32 FreeLibrary().
820 // On Success: A non-zero number
823 PBD_API int PBD_APICALLTYPE
824 dlclose (void *handle)
826 return (::FreeLibrary((HMODULE)handle));
830 //***************************************************************
834 // Emulates POSIX dlsym() using Win32 GetProcAddress().
838 // On Success: A pointer to the found function or symbol
841 PBD_API void* PBD_APICALLTYPE
842 dlsym (void *handle, const char *symbol_name)
844 // First test for RTLD_DEFAULT and RTLD_NEXT
845 if ((handle == 0/*RTLD_DEFAULT*/) || (handle == ((void *) -1L)/*RTLD_NEXT*/))
847 return 0; // Not yet supported for Win32
850 return (::GetProcAddress((HMODULE)handle, symbol_name));
853 #define LOCAL_ERROR_BUF_SIZE 1024
854 static char szLastWinError[LOCAL_ERROR_BUF_SIZE];
855 //***************************************************************
859 // Emulates POSIX dlerror() using Win32 GetLastError().
863 // On Success: The translated message corresponding to the
865 // On Failure: NULL (if the last error was ERROR_SUCCESS)
867 PBD_API char* PBD_APICALLTYPE
870 DWORD dwLastErrorId = GetLastError();
871 if (ERROR_SUCCESS == dwLastErrorId)
875 if (0 == FormatMessage(
876 FORMAT_MESSAGE_FROM_SYSTEM,
881 LOCAL_ERROR_BUF_SIZE,
884 sprintf(szLastWinError, "Could not decipher the previous error message");
887 // POSIX dlerror() seems to reset the
888 // error system, so emulate that here
889 SetLastError(ERROR_SUCCESS);
892 return(szLastWinError);
895 #endif // COMPILER_MSVC