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
37 #include <pbd/error.h>
38 #include <ardourext/misc.h>
39 #include <ardourext/pthread.h> // Should ensure that we include the right
40 // version - but we'll check anyway, later
44 #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
48 int tz_minuteswest; /* minutes W of Greenwich */
49 int tz_dsttime; /* type of dst correction */
52 LIBPBD_API int PBD_APICALLTYPE
53 gettimeofday(struct timeval *__restrict tv, __timezone_ptr_t tz) // Does this need to be exported ?
56 unsigned __int64 tmpres = 0;
57 static int tzflag = 0;
61 GetSystemTimeAsFileTime(&ft);
63 tmpres |= ft.dwHighDateTime;
65 tmpres |= ft.dwLowDateTime;
67 /*converting file time to unix epoch*/
68 tmpres /= 10; /*convert into microseconds*/
69 tmpres -= DELTA_EPOCH_IN_MICROSECS;
70 tv->tv_sec = (long)(tmpres / 1000000UL);
71 tv->tv_usec = (long)(tmpres % 1000000UL);
76 struct timezone *ptz = static_cast<struct timezone*> (tz);
84 ptz->tz_minuteswest = _timezone / 60;
85 ptz->tz_dsttime = _daylight;
92 // Define the default comparison operators for Windows (ptw32) 'pthread_t' (not used
93 // by Ardour AFAIK but would be needed if an array of 'pthread_t' had to be sorted).
94 #ifndef PTHREAD_H // Defined by PTW32 (Linux and other versions define _PTHREAD_H)
95 #error "An incompatible version of 'pthread.h' is #included. Use only the Windows (ptw32) version!"
97 LIBPBD_API bool operator> (const pthread_t& lhs, const pthread_t& rhs)
99 return (std::greater<void*>()(lhs.p, rhs.p));
102 LIBPBD_API bool operator< (const pthread_t& lhs, const pthread_t& rhs)
104 return (std::less<void*>()(lhs.p, rhs.p));
107 LIBPBD_API bool operator!= (const pthread_t& lhs, const pthread_t& rhs)
109 return (std::not_equal_to<void*>()(lhs.p, rhs.p));
112 LIBPBD_API bool operator== (const pthread_t& lhs, const pthread_t& rhs)
114 return (!(lhs != rhs));
118 // Functions supplied (later) to std::transform
119 //***************************************************************
121 // invert_backslash()
123 // Examines a supplied ASCII character and (if the character is
124 // a backslash) converts it to a forward slash,
128 // The supplied character (converted, if it was a backslash)
130 char invert_backslash(char character)
132 if ('\\' == character)
138 //***************************************************************
140 // invert_forwardslash()
142 // Examines a supplied ASCII character and (if the character is
143 // a forward slash) converts it to a backslash,
147 // The supplied character (converted, if it was a fwd slash)
149 char invert_forwardslash(char character)
151 if ('/' == character)
158 //***************************************************************
162 // Emulates pread() using _lseek()/_read()/_lseek().
166 // On Success: The number of bytes read from the file
169 LIBPBD_API ssize_t PBD_APICALLTYPE
170 pread(int handle, void *buf, size_t nbytes, off_t offset)
175 off_t old_offset = _tell(handle);
181 _lseek(handle, offset, SEEK_SET);
182 ret = _read(handle, buf, nbytes);
185 _lseek(handle, old_offset, SEEK_SET);
193 //***************************************************************
197 // Emulates pwrite() using _lseek()/_write()/_lseek().
201 // On Success: The number of bytes written to the file
204 LIBPBD_API ssize_t PBD_APICALLTYPE
205 pwrite(int handle, const void *buf, size_t nbytes, off_t offset)
210 off_t old_offset = _lseek(handle, offset, SEEK_SET);
216 ret = _write(handle, buf, nbytes);
219 _lseek(handle, old_offset, SEEK_SET);
226 //***************************************************************
230 // Emulates round() using floor().
234 // On Success: The largest integer that is less than or
238 LIBPBD_API double PBD_APICALLTYPE
246 //***************************************************************
248 // TestForMinimumSpecOS()
250 // Tests the user's OS to see if it is Win2K or later (could be
251 // expanded quite easily to accommodate other OS's)
255 // On Success: TRUE (if the user's OS matches the minimum spec)
256 // On Failure: FALSE otherwise
258 LIBPBD_API bool PBD_APICALLTYPE
259 TestForMinimumSpecOS(char *revision /* currently ignored */)
262 #ifdef PLATFORM_WINDOWS
264 HINSTANCE hKernelDll = (HINSTANCE)dlopen("kernel32.dll", RTLD_NOW);
268 // 'CreateHardLink()' is only available from Win2K onwards.
269 if (NULL != dlsym(hKernelDll, "CreateHardLinkA"))
275 // Other OS's could be accommodated here
281 //***************************************************************
285 // Emulates POSIX realpath() using Win32 _fullpath().
289 // On Success: A pointer to the resolved (absolute) path
292 LIBPBD_API char* PBD_APICALLTYPE
293 realpath (const char *original_path, char resolved_path[_MAX_PATH+1])
296 bool bIsSymLink = 0; // We'll probably need to test the incoming path
297 // to find out if it points to a Windows shortcut
298 // (or a hard link) and set this appropriately.
301 // At the moment I'm not sure if Windows '_fullpath()' is directly
302 // equivalent to POSIX 'realpath()' - in as much as the latter will
303 // resolve the supplied path if it happens to point to a symbolic
304 // link ('_fullpath()' probably DOESN'T do this but I'm not really
305 // sure if Ardour needs such functionality anyway). Therefore we'll
306 // possibly need to add that functionality here at a later date.
310 char temp[(MAX_PATH+1)*6]; // Allow for maximum length of a path in UTF8 characters
312 // POSIX 'realpath()' requires that the buffer size is at
313 // least PATH_MAX+1, so assume that the user knew this !!
314 pRet = _fullpath(temp, Glib::locale_from_utf8(original_path).c_str(), _MAX_PATH);
316 strcpy(resolved_path, Glib::locale_to_utf8(temp).c_str());
323 //***************************************************************
327 // Creates a pointer to a DIR structure, appropriately filled in
328 // and ready to begin a directory search iteration.
332 // On Success: Pointer to a (heap based) DIR structure
335 LIBPBD_API DIR* PBD_APICALLTYPE
336 opendir (const char *szPath)
338 wchar_t wpath[PATH_MAX+1];
347 if ((!errno) && ('\0' == szPath[0]))
350 // Determine if the given path really is a directory
353 if (0 == MultiByteToWideChar (CP_UTF8, 0, (LPCSTR)szPath, -1, (LPWSTR)wpath, sizeof(wpath)))
356 if ((!errno) && ((rc = GetFileAttributesW(wpath)) == -1))
359 if ((!errno) && (!(rc & FILE_ATTRIBUTE_DIRECTORY)))
360 // Error. Entry exists but not a directory. */
365 // Allocate enough memory to store DIR structure, plus
366 // the complete directory path originally supplied.
367 pDir = (DIR *)malloc(sizeof(DIR) + strlen(szPath) + strlen("\\") + strlen ("*"));
371 // Error - out of memory
378 // Create the search expression
379 strcpy(pDir->dd_name, szPath);
381 // Add a backslash if the path doesn't already end with one
382 if (pDir->dd_name[0] != '\0' &&
383 pDir->dd_name[strlen(pDir->dd_name) - 1] != '/' &&
384 pDir->dd_name[strlen(pDir->dd_name) - 1] != '\\')
386 strcat (pDir->dd_name, "\\");
389 // Add the search pattern
390 strcat(pDir->dd_name, "*");
392 // Initialize handle to -1 so that a premature closedir()
393 // doesn't try to call _findclose() on it.
394 pDir->dd_handle = (-1);
396 // Initialize the status
399 // Initialize the dirent structure. 'ino' and 'reclen' are invalid under Win32
400 // and 'name' simply points at the appropriate part of the findfirst_t struct.
401 pDir->dd_dir.d_ino = 0;
402 pDir->dd_dir.d_reclen = 0;
403 pDir->dd_dir.d_namlen = 0;
404 strcpy(pDir->dd_dir.d_name, pDir->dd_dta.name);
406 return (pDir); // Succeeded
411 return (DIR *) 0; // Failed
415 //***************************************************************
419 // Return a pointer to a dirent struct, filled with information
420 // about the next entry in the directory.
424 // On Success: A pointer to the supplied DIR's 'dirent' struct
427 LIBPBD_API struct dirent* PBD_APICALLTYPE
433 // Check for valid DIR struct
437 if ((strcmp(pDir->dd_dir.d_name, pDir->dd_dta.name)) && (!errno))
438 // The structure does not seem to be set up correctly
442 if (pDir->dd_stat < 0)
444 // We have already returned all files in this directory
445 // (or the structure has an invalid dd_stat).
446 return (struct dirent *)0;
448 else if (pDir->dd_stat == 0)
450 // We haven't started the search yet.
452 pDir->dd_handle = _findfirst (Glib::locale_from_utf8(pDir->dd_name).c_str(), &(pDir->dd_dta));
454 if (pDir->dd_handle == -1)
455 // The directory is empty
462 // Do not return ENOENT on last file in directory
465 // Get the next search entry
466 if (_findnext (pDir->dd_handle, &(pDir->dd_dta)))
468 // We are off the end or otherwise error
470 _findclose (pDir->dd_handle);
471 pDir->dd_handle = -1;
475 // Update to indicate the correct status number
479 if (pDir->dd_stat > 0)
481 // We successfully got an entry. Details about the file are
482 // already appropriately filled in except for the length of
484 strcpy(pDir->dd_dir.d_name, pDir->dd_dta.name);
485 pDir->dd_dir.d_namlen = strlen (pDir->dd_dir.d_name);
486 return (&pDir->dd_dir); // Succeeded
490 return (struct dirent *) 0; // Failed
494 //***************************************************************
498 // Frees the resources allocated by opendir().
505 LIBPBD_API int PBD_APICALLTYPE
516 if ((-1) != pDir->dd_handle)
517 rc = _findclose (pDir->dd_handle);
519 // Free the DIR structure
522 return rc; // Succeeded
525 return (-1); // Failed
528 //***************************************************************
532 // Emulates Linux mkstemp() using Win32 _mktemp() and _open() etc.
536 // On Success: A file descriptor for the opened file.
539 LIBPBD_API int PBD_APICALLTYPE
540 mkstemp (char *template_name)
544 char szTempPath[PATH_MAX+100]; // Just ensure we have plenty of buffer space
546 if (NULL != (szFileName = _mktemp(template_name)))
548 if (0 != ::GetTempPathA(sizeof(szTempPath), szTempPath))
550 strcat(szTempPath, szFileName);
551 ret = _open(szTempPath, (_O_CREAT|_O_BINARY|_O_TEMPORARY|_O_RDWR|_O_TRUNC), _S_IWRITE);
559 //***************************************************************
563 // Emulates Linux link() using Win32 CreateHardLink()(NTFS only).
567 // On Success: Non-zero.
568 // On Failure: Zero (call 'GetLastError()' to retrieve info)
570 LIBPBD_API int PBD_APICALLTYPE
571 ntfs_link (const char *existing_filepath, const char *link_filepath)
573 int ret = 1; // 'ERROR_INVALID_FUNCTION'
574 bool bValidPath = false;
576 // Make sure we've been sent a valid input string
577 if (existing_filepath && link_filepath)
579 std::string strRoot = existing_filepath;
581 if ((1 < strRoot.length()) && ('\\' == existing_filepath[0]) && ('\\' == existing_filepath[1]))
585 // We've been sent a network path. Convert backslashes to forward slashes temporarily.
586 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
588 // Now, if there are less than four slashes, add a fourth one or abort
589 std::string::iterator iter = strRoot.begin();
590 while ((slashcnt < 4) && (iter != strRoot.end()))
600 // If only 3 slashes were counted, add a trailing slash
604 // Now find the position of the fourth slash
605 iter = strRoot.begin();
607 for (slashcnt=0; slashcnt<4;)
614 if (++iter == strRoot.end())
618 strRoot.resize(charcnt);
624 // Assume a standard Windows style path
625 if (1 < strRoot.length() && (':' == existing_filepath[1]))
627 // Convert backslashes to forward slashes temporarily.
628 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
630 if (2 == strRoot.length())
633 if ('/' == strRoot[2])
643 char szFileSystemType[_MAX_PATH+1];
645 // Restore the original backslashes
646 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_forwardslash);
648 // Windows only supports hard links for the NTFS filing
649 // system, so let's make sure that's what we're using!!
650 if (::GetVolumeInformationA(strRoot.c_str(), NULL, 0, NULL, NULL, NULL, szFileSystemType, _MAX_PATH+1))
652 std::string strRootFileSystemType = szFileSystemType;
653 std::transform(strRootFileSystemType.begin(), strRootFileSystemType.end(), strRootFileSystemType.begin(), ::toupper);
654 #if (_WIN32_WINNT >= 0x0500)
655 if (0 == strRootFileSystemType.compare("NTFS"))
657 if (TestForMinimumSpecOS()) // Hard links were only available from Win2K onwards
658 if (0 == CreateHardLinkA(link_filepath, existing_filepath, NULL))
659 { // Note that the above API call cannot create a link to a directory, so
660 // should we also be checking that the supplied path was actually a file?
661 ret = GetLastError();
664 SetLastError(ret = 0); // 'NO_ERROR'
668 ret = 4300; // 'ERROR_INVALID_MEDIA'
674 ret = 123; // 'ERROR_INVALID_NAME'
677 ret = 161; // 'ERROR_BAD_PATHNAME'
689 //***************************************************************
693 // Emulates Linux unlink() using Win32 DeleteFile()(NTFS only).
697 // On Success: Non-zero.
698 // On Failure: Zero (call 'GetLastError()' to retrieve info)
700 LIBPBD_API int PBD_APICALLTYPE
701 ntfs_unlink (const char *link_filepath)
703 int ret = 1; // 'ERROR_INVALID_FUNCTION'
704 bool bValidPath = false;
706 // Make sure we've been sent a valid input string
709 std::string strRoot = link_filepath;
711 if ((1 < strRoot.length()) && ('\\' == link_filepath[0]) && ('\\' == link_filepath[1]))
715 // We've been sent a network path. Convert backslashes to forward slashes temporarily.
716 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
718 // Now, if there are less than four slashes, add a fourth one or abort
719 std::string::iterator iter = strRoot.begin();
720 while ((slashcnt < 4) && (iter != strRoot.end()))
730 // If only 3 slashes were counted, add a trailing slash
734 // Now find the position of the fourth slash
735 iter = strRoot.begin();
737 for (slashcnt=0; slashcnt<4;)
744 if (++iter == strRoot.end())
748 strRoot.resize(charcnt);
754 // Assume a standard Windows style path
755 if (1 < strRoot.length() && (':' == link_filepath[1]))
757 // Convert backslashes to forward slashes temporarily.
758 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
760 if (2 == strRoot.length())
763 if ('/' == strRoot[2])
773 char szFileSystemType[_MAX_PATH+1];
775 // Restore the original backslashes
776 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_forwardslash);
778 // Windows only supports hard links for the NTFS filing
779 // system, so let's make sure that's what we're using!!
780 if (::GetVolumeInformationA(strRoot.c_str(), NULL, 0, NULL, NULL, NULL, szFileSystemType, _MAX_PATH+1))
782 std::string strRootFileSystemType = szFileSystemType;
783 std::transform(strRootFileSystemType.begin(), strRootFileSystemType.end(), strRootFileSystemType.begin(), ::toupper);
784 #if (_WIN32_WINNT >= 0x0500)
785 if (0 == strRootFileSystemType.compare("NTFS"))
786 if (TestForMinimumSpecOS()) // Hard links were only available from Win2K onwards
787 if (0 == DeleteFileA(link_filepath))
788 ret = GetLastError();
790 ret = 0; // 'NO_ERROR'
795 ret = 123; // 'ERROR_INVALID_NAME'
798 ret = 161; // 'ERROR_BAD_PATHNAME'
812 //***************************************************************
816 // Emulates POSIX dlopen() using Win32 LoadLibrary().
820 // On Success: A handle to the opened DLL
823 LIBPBD_API void* PBD_APICALLTYPE
824 dlopen (const char *file_name, int mode)
826 // Note that 'mode' is ignored in Win32
827 return(::LoadLibraryA(Glib::locale_from_utf8(file_name).c_str()));
831 //***************************************************************
835 // Emulates POSIX dlclose() using Win32 FreeLibrary().
839 // On Success: A non-zero number
842 LIBPBD_API int PBD_APICALLTYPE
843 dlclose (void *handle)
845 return (::FreeLibrary((HMODULE)handle));
849 //***************************************************************
853 // Emulates POSIX dlsym() using Win32 GetProcAddress().
857 // On Success: A pointer to the found function or symbol
860 LIBPBD_API void* PBD_APICALLTYPE
861 dlsym (void *handle, const char *symbol_name)
863 // First test for RTLD_DEFAULT and RTLD_NEXT
864 if ((handle == 0/*RTLD_DEFAULT*/) || (handle == ((void *) -1L)/*RTLD_NEXT*/))
866 return 0; // Not yet supported for Win32
869 return (::GetProcAddress((HMODULE)handle, symbol_name));
872 #define LOCAL_ERROR_BUF_SIZE 1024
873 static char szLastWinError[LOCAL_ERROR_BUF_SIZE];
874 //***************************************************************
878 // Emulates POSIX dlerror() using Win32 GetLastError().
882 // On Success: The translated message corresponding to the
884 // On Failure: NULL (if the last error was ERROR_SUCCESS)
886 LIBPBD_API char* PBD_APICALLTYPE
889 DWORD dwLastErrorId = GetLastError();
890 if (ERROR_SUCCESS == dwLastErrorId)
894 if (0 == FormatMessage(
895 FORMAT_MESSAGE_FROM_SYSTEM,
900 LOCAL_ERROR_BUF_SIZE,
903 sprintf(szLastWinError, "Could not decipher the previous error message");
906 // POSIX dlerror() seems to reset the
907 // error system, so emulate that here
908 SetLastError(ERROR_SUCCESS);
911 return(szLastWinError);
914 #endif // COMPILER_MSVC