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
244 //***************************************************************
248 // Emulates trunc() using floor() and ceil().
252 // On Success: The largest integer whose magnitude is less
253 // than or equal to 'x' (regardless of sign).
256 LIBPBD_API double PBD_APICALLTYPE
265 #if defined(_MSC_VER) && (_MSC_VER < 1800)
266 //***************************************************************
270 // Emulates C99 expm1() using exp().
274 // On Success: (('e' raised to the power of 'x') - 1)
275 // (e.g. expm1(1) == 1.7182818).
276 // On Failure: None, except that calling exp(x) should generate
277 // an appropriate error for us (such as INF etc).
279 LIBPBD_API double PBD_APICALLTYPE
282 return (exp(x) - (double)1.0);
285 //***************************************************************
289 // Emulates C99 log1p() using log().
293 // On Success: The natural logarithm of (1 + x)
294 // (e.g. log1p(1) == 0.69314718).
295 // On Failure: None, except that calling log(x) should generate
296 // an appropriate error for us (such as ERANGE etc).
298 LIBPBD_API double PBD_APICALLTYPE
301 return (log(x + (double)1.0));
305 #if defined(_MSC_VER) && (_MSC_VER < 1900)
306 //***************************************************************
310 // Emulates C99 log2() using log().
314 // On Success: The binary (base-2) logarithm of 'x'
315 // (e.g. log2(1024) == 10).
316 // On Failure: None, except that calling log(x) should generate
317 // an appropriate error for us (such as ERANGE etc).
319 LIBPBD_API double PBD_APICALLTYPE
322 return (log(x) / log((double)2.0));
328 //***************************************************************
330 // TestForMinimumSpecOS()
332 // Tests the user's OS to see if it is Win2K or later (could be
333 // expanded quite easily to accommodate other OS's)
337 // On Success: TRUE (if the user's OS matches the minimum spec)
338 // On Failure: FALSE otherwise
340 LIBPBD_API bool PBD_APICALLTYPE
341 TestForMinimumSpecOS(char *revision /* currently ignored */)
344 #ifdef PLATFORM_WINDOWS
346 HINSTANCE hKernelDll = (HINSTANCE)dlopen("kernel32.dll", RTLD_NOW);
350 // 'CreateHardLink()' is only available from Win2K onwards.
351 if (NULL != dlsym(hKernelDll, "CreateHardLinkA"))
357 // Other OS's could be accommodated here
363 //***************************************************************
367 // Emulates POSIX realpath() using Win32 _fullpath().
371 // On Success: A pointer to the resolved (absolute) path
374 LIBPBD_API char* PBD_APICALLTYPE
375 realpath (const char *original_path, char resolved_path[_MAX_PATH+1])
378 bool bIsSymLink = 0; // We'll probably need to test the incoming path
379 // to find out if it points to a Windows shortcut
380 // (or a hard link) and set this appropriately.
383 // At the moment I'm not sure if Windows '_fullpath()' is directly
384 // equivalent to POSIX 'realpath()' - in as much as the latter will
385 // resolve the supplied path if it happens to point to a symbolic
386 // link ('_fullpath()' probably DOESN'T do this but I'm not really
387 // sure if Ardour needs such functionality anyway). Therefore we'll
388 // possibly need to add that functionality here at a later date.
392 char temp[(MAX_PATH+1)*6]; // Allow for maximum length of a path in UTF8 characters
394 // POSIX 'realpath()' requires that the buffer size is at
395 // least PATH_MAX+1, so assume that the user knew this !!
396 pRet = _fullpath(temp, Glib::locale_from_utf8(original_path).c_str(), _MAX_PATH);
398 strcpy(resolved_path, Glib::locale_to_utf8(temp).c_str());
405 //***************************************************************
409 // Creates a pointer to a DIR structure, appropriately filled in
410 // and ready to begin a directory search iteration.
414 // On Success: Pointer to a (heap based) DIR structure
417 LIBPBD_API DIR* PBD_APICALLTYPE
418 opendir (const char *szPath)
420 wchar_t wpath[PATH_MAX+1];
429 if ((!errno) && ('\0' == szPath[0]))
432 // Determine if the given path really is a directory
435 if (0 == MultiByteToWideChar (CP_UTF8, 0, (LPCSTR)szPath, -1, (LPWSTR)wpath, sizeof(wpath)))
438 if ((!errno) && ((rc = GetFileAttributesW(wpath)) == -1))
441 if ((!errno) && (!(rc & FILE_ATTRIBUTE_DIRECTORY)))
442 // Error. Entry exists but not a directory. */
447 // Allocate enough memory to store DIR structure, plus
448 // the complete directory path originally supplied.
449 pDir = (DIR *)malloc(sizeof(DIR) + strlen(szPath) + strlen("\\") + strlen ("*"));
453 // Error - out of memory
460 // Create the search expression
461 strcpy(pDir->dd_name, szPath);
463 // Add a backslash if the path doesn't already end with one
464 if (pDir->dd_name[0] != '\0' &&
465 pDir->dd_name[strlen(pDir->dd_name) - 1] != '/' &&
466 pDir->dd_name[strlen(pDir->dd_name) - 1] != '\\')
468 strcat (pDir->dd_name, "\\");
471 // Add the search pattern
472 strcat(pDir->dd_name, "*");
474 // Initialize handle to -1 so that a premature closedir()
475 // doesn't try to call _findclose() on it.
476 pDir->dd_handle = (-1);
478 // Initialize the status
481 // Initialize the dirent structure. 'ino' and 'reclen' are invalid under Win32
482 // and 'name' simply points at the appropriate part of the findfirst_t struct.
483 pDir->dd_dir.d_ino = 0;
484 pDir->dd_dir.d_reclen = 0;
485 pDir->dd_dir.d_namlen = 0;
486 strcpy(pDir->dd_dir.d_name, pDir->dd_dta.name);
488 return (pDir); // Succeeded
493 return (DIR *) 0; // Failed
497 //***************************************************************
501 // Return a pointer to a dirent struct, filled with information
502 // about the next entry in the directory.
506 // On Success: A pointer to the supplied DIR's 'dirent' struct
509 LIBPBD_API struct dirent* PBD_APICALLTYPE
515 // Check for valid DIR struct
519 if ((strcmp(pDir->dd_dir.d_name, pDir->dd_dta.name)) && (!errno))
520 // The structure does not seem to be set up correctly
524 if (pDir->dd_stat < 0)
526 // We have already returned all files in this directory
527 // (or the structure has an invalid dd_stat).
528 return (struct dirent *)0;
530 else if (pDir->dd_stat == 0)
532 // We haven't started the search yet.
534 pDir->dd_handle = _findfirst (Glib::locale_from_utf8(pDir->dd_name).c_str(), &(pDir->dd_dta));
536 if (pDir->dd_handle == -1)
537 // The directory is empty
544 // Do not return ENOENT on last file in directory
547 // Get the next search entry
548 if (_findnext (pDir->dd_handle, &(pDir->dd_dta)))
550 // We are off the end or otherwise error
552 _findclose (pDir->dd_handle);
553 pDir->dd_handle = -1;
557 // Update to indicate the correct status number
561 if (pDir->dd_stat > 0)
563 // We successfully got an entry. Details about the file are
564 // already appropriately filled in except for the length of
566 strcpy(pDir->dd_dir.d_name, pDir->dd_dta.name);
567 pDir->dd_dir.d_namlen = strlen (pDir->dd_dir.d_name);
568 return (&pDir->dd_dir); // Succeeded
572 return (struct dirent *) 0; // Failed
576 //***************************************************************
580 // Frees the resources allocated by opendir().
587 LIBPBD_API int PBD_APICALLTYPE
598 if ((-1) != pDir->dd_handle)
599 rc = _findclose (pDir->dd_handle);
601 // Free the DIR structure
604 return rc; // Succeeded
607 return (-1); // Failed
610 //***************************************************************
614 // Emulates Linux mkstemp() using Win32 _mktemp() and _open() etc.
618 // On Success: A file descriptor for the opened file.
621 LIBPBD_API int PBD_APICALLTYPE
622 mkstemp (char *template_name)
626 char szTempPath[PATH_MAX+100]; // Just ensure we have plenty of buffer space
628 if (NULL != (szFileName = _mktemp(template_name)))
630 if (0 != ::GetTempPathA(sizeof(szTempPath), szTempPath))
632 strcat(szTempPath, szFileName);
633 ret = _open(szTempPath, (_O_CREAT|_O_BINARY|_O_TEMPORARY|_O_RDWR|_O_TRUNC), _S_IWRITE);
641 //***************************************************************
645 // Emulates Linux link() using Win32 CreateHardLink()(NTFS only).
649 // On Success: Non-zero.
650 // On Failure: Zero (call 'GetLastError()' to retrieve info)
652 LIBPBD_API int PBD_APICALLTYPE
653 ntfs_link (const char *existing_filepath, const char *link_filepath)
655 int ret = 1; // 'ERROR_INVALID_FUNCTION'
656 bool bValidPath = false;
658 // Make sure we've been sent a valid input string
659 if (existing_filepath && link_filepath)
661 std::string strRoot = existing_filepath;
663 if ((1 < strRoot.length()) && ('\\' == existing_filepath[0]) && ('\\' == existing_filepath[1]))
667 // We've been sent a network path. Convert backslashes to forward slashes temporarily.
668 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
670 // Now, if there are less than four slashes, add a fourth one or abort
671 std::string::iterator iter = strRoot.begin();
672 while ((slashcnt < 4) && (iter != strRoot.end()))
682 // If only 3 slashes were counted, add a trailing slash
686 // Now find the position of the fourth slash
687 iter = strRoot.begin();
689 for (slashcnt=0; slashcnt<4;)
696 if (++iter == strRoot.end())
700 strRoot.resize(charcnt);
706 // Assume a standard Windows style path
707 if (1 < strRoot.length() && (':' == existing_filepath[1]))
709 // Convert backslashes to forward slashes temporarily.
710 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
712 if (2 == strRoot.length())
715 if ('/' == strRoot[2])
725 char szFileSystemType[_MAX_PATH+1];
727 // Restore the original backslashes
728 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_forwardslash);
730 // Windows only supports hard links for the NTFS filing
731 // system, so let's make sure that's what we're using!!
732 if (::GetVolumeInformationA(strRoot.c_str(), NULL, 0, NULL, NULL, NULL, szFileSystemType, _MAX_PATH+1))
734 std::string strRootFileSystemType = szFileSystemType;
735 std::transform(strRootFileSystemType.begin(), strRootFileSystemType.end(), strRootFileSystemType.begin(), ::toupper);
736 #if (_WIN32_WINNT >= 0x0500)
737 if (0 == strRootFileSystemType.compare("NTFS"))
739 if (TestForMinimumSpecOS()) // Hard links were only available from Win2K onwards
740 if (0 == CreateHardLinkA(link_filepath, existing_filepath, NULL))
741 { // Note that the above API call cannot create a link to a directory, so
742 // should we also be checking that the supplied path was actually a file?
743 ret = GetLastError();
746 SetLastError(ret = 0); // 'NO_ERROR'
750 ret = 4300; // 'ERROR_INVALID_MEDIA'
756 ret = 123; // 'ERROR_INVALID_NAME'
759 ret = 161; // 'ERROR_BAD_PATHNAME'
771 //***************************************************************
775 // Emulates Linux unlink() using Win32 DeleteFile()(NTFS only).
779 // On Success: Non-zero.
780 // On Failure: Zero (call 'GetLastError()' to retrieve info)
782 LIBPBD_API int PBD_APICALLTYPE
783 ntfs_unlink (const char *link_filepath)
785 int ret = 1; // 'ERROR_INVALID_FUNCTION'
786 bool bValidPath = false;
788 // Make sure we've been sent a valid input string
791 std::string strRoot = link_filepath;
793 if ((1 < strRoot.length()) && ('\\' == link_filepath[0]) && ('\\' == link_filepath[1]))
797 // We've been sent a network path. Convert backslashes to forward slashes temporarily.
798 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
800 // Now, if there are less than four slashes, add a fourth one or abort
801 std::string::iterator iter = strRoot.begin();
802 while ((slashcnt < 4) && (iter != strRoot.end()))
812 // If only 3 slashes were counted, add a trailing slash
816 // Now find the position of the fourth slash
817 iter = strRoot.begin();
819 for (slashcnt=0; slashcnt<4;)
826 if (++iter == strRoot.end())
830 strRoot.resize(charcnt);
836 // Assume a standard Windows style path
837 if (1 < strRoot.length() && (':' == link_filepath[1]))
839 // Convert backslashes to forward slashes temporarily.
840 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_backslash);
842 if (2 == strRoot.length())
845 if ('/' == strRoot[2])
855 char szFileSystemType[_MAX_PATH+1];
857 // Restore the original backslashes
858 std::transform(strRoot.begin(), strRoot.end(), strRoot.begin(), invert_forwardslash);
860 // Windows only supports hard links for the NTFS filing
861 // system, so let's make sure that's what we're using!!
862 if (::GetVolumeInformationA(strRoot.c_str(), NULL, 0, NULL, NULL, NULL, szFileSystemType, _MAX_PATH+1))
864 std::string strRootFileSystemType = szFileSystemType;
865 std::transform(strRootFileSystemType.begin(), strRootFileSystemType.end(), strRootFileSystemType.begin(), ::toupper);
866 #if (_WIN32_WINNT >= 0x0500)
867 if (0 == strRootFileSystemType.compare("NTFS"))
868 if (TestForMinimumSpecOS()) // Hard links were only available from Win2K onwards
869 if (0 == DeleteFileA(link_filepath))
870 ret = GetLastError();
872 ret = 0; // 'NO_ERROR'
877 ret = 123; // 'ERROR_INVALID_NAME'
880 ret = 161; // 'ERROR_BAD_PATHNAME'
894 //***************************************************************
898 // Emulates POSIX dlopen() using Win32 LoadLibrary().
902 // On Success: A handle to the opened DLL
905 LIBPBD_API void* PBD_APICALLTYPE
906 dlopen (const char *file_name, int mode)
908 // Note that 'mode' is ignored in Win32
909 return(::LoadLibraryA(Glib::locale_from_utf8(file_name).c_str()));
913 //***************************************************************
917 // Emulates POSIX dlclose() using Win32 FreeLibrary().
921 // On Success: A non-zero number
924 LIBPBD_API int PBD_APICALLTYPE
925 dlclose (void *handle)
927 return (::FreeLibrary((HMODULE)handle));
931 //***************************************************************
935 // Emulates POSIX dlsym() using Win32 GetProcAddress().
939 // On Success: A pointer to the found function or symbol
942 LIBPBD_API void* PBD_APICALLTYPE
943 dlsym (void *handle, const char *symbol_name)
945 // First test for RTLD_DEFAULT and RTLD_NEXT
946 if ((handle == 0/*RTLD_DEFAULT*/) || (handle == ((void *) -1L)/*RTLD_NEXT*/))
948 return 0; // Not yet supported for Win32
951 return (::GetProcAddress((HMODULE)handle, symbol_name));
954 #define LOCAL_ERROR_BUF_SIZE 1024
955 static char szLastWinError[LOCAL_ERROR_BUF_SIZE];
956 //***************************************************************
960 // Emulates POSIX dlerror() using Win32 GetLastError().
964 // On Success: The translated message corresponding to the
966 // On Failure: NULL (if the last error was ERROR_SUCCESS)
968 LIBPBD_API char* PBD_APICALLTYPE
971 DWORD dwLastErrorId = GetLastError();
972 if (ERROR_SUCCESS == dwLastErrorId)
976 if (0 == FormatMessage(
977 FORMAT_MESSAGE_FROM_SYSTEM,
982 LOCAL_ERROR_BUF_SIZE,
985 sprintf(szLastWinError, "Could not decipher the previous error message");
988 // POSIX dlerror() seems to reset the
989 // error system, so emulate that here
990 SetLastError(ERROR_SUCCESS);
993 return(szLastWinError);
996 #endif // COMPILER_MSVC