GNU Octave 11.1.0
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
 
Loading...
Searching...
No Matches
oct-sysdep.cc
Go to the documentation of this file.
1////////////////////////////////////////////////////////////////////////
2//
3// Copyright (C) 1996-2026 The Octave Project Developers
4//
5// See the file COPYRIGHT.md in the top-level directory of this
6// distribution or <https://octave.org/copyright/>.
7//
8// This file is part of Octave.
9//
10// Octave is free software: you can redistribute it and/or modify it
11// under the terms of the GNU General Public License as published by
12// the Free Software Foundation, either version 3 of the License, or
13// (at your option) any later version.
14//
15// Octave is distributed in the hope that it will be useful, but
16// WITHOUT ANY WARRANTY; without even the implied warranty of
17// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18// GNU General Public License for more details.
19//
20// You should have received a copy of the GNU General Public License
21// along with Octave; see the file COPYING. If not, see
22// <https://www.gnu.org/licenses/>.
23//
24////////////////////////////////////////////////////////////////////////
25
26#if defined (HAVE_CONFIG_H)
27# include "config.h"
28#endif
29
30#include <cstdlib>
31#include <locale>
32#include <codecvt>
33
34#if defined (OCTAVE_USE_WINDOWS_API)
35# include <iostream>
36
37# include <windows.h>
38# include <wchar.h>
39#endif
40
41#include "dir-ops.h"
42#include "file-ops.h"
43#include "file-stat.h"
45#include "oct-error.h"
46#include "oct-sysdep.h"
47#include "setenv-wrapper.h"
48#include "uniconv-wrappers.h"
49#include "unistd-wrappers.h"
50#include "unsetenv-wrapper.h"
51
52#if defined (OCTAVE_USE_WINDOWS_API)
53# include "filepos-wrappers.h"
54# include "oct-hash.h"
55# include "oct-locbuf.h"
56# include "unwind-prot.h"
57#endif
58
61
62int
63system (const std::string& cmd_str)
64{
65#if defined (OCTAVE_USE_WINDOWS_API)
66
67 // On Windows (non-Cygwin), child processes need to be created with a new
68 // console to avoid desynchronization of the console that is used by the
69 // command window widget of the GUI.
70
71 // Capture output using pipe.
72 HANDLE h_read;
73 HANDLE h_write;
74 SECURITY_ATTRIBUTES sa {};
75 sa.nLength = sizeof (sa);
76 sa.bInheritHandle = TRUE; // child can inherit
77 sa.lpSecurityDescriptor = nullptr;
78
79 if (! CreatePipe (&h_read, &h_write, &sa, 0))
80 return GetLastError ();
81
82 // avoid inheriting read end of the pipe
83 SetHandleInformation (h_read, HANDLE_FLAG_INHERIT, 0);
84
85 // create process with new hidden console
86 std::wstring wcmd_str {L"cmd.exe /C \""};
87 wcmd_str.append (u8_to_wstring (cmd_str));
88 wcmd_str.append (L"\"");
89 STARTUPINFOW si {};
90 si.cb = sizeof (si);
91 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
92 si.wShowWindow = SW_HIDE; // avoid flashing black window
93 si.hStdOutput = h_write;
94 si.hStdError = h_write;
95 si.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
96 PROCESS_INFORMATION pi {};
97
98 BOOL ok = CreateProcessW (nullptr, &wcmd_str[0], nullptr, nullptr, TRUE,
99 CREATE_NEW_CONSOLE, nullptr, nullptr, &si, &pi);
100
101 CloseHandle (h_write);
102
103 if (! ok)
104 {
105 CloseHandle (h_read);
106 return GetLastError ();
107 }
108
109 // read from pipe (in chunks)
110 char buffer[4096];
111 DWORD bytes_read;
112 while (ReadFile (h_read, buffer, sizeof (buffer)-1, &bytes_read, nullptr)
113 && bytes_read > 0)
114 {
115 buffer[bytes_read] = '\0';
116 std::cout << buffer;
117 }
118
119 WaitForSingleObject (pi.hProcess, INFINITE);
120
121 DWORD ret = 0;
122 GetExitCodeProcess (pi.hProcess, &ret);
123
124 CloseHandle (pi.hProcess);
125 CloseHandle (pi.hThread);
126 CloseHandle (h_read);
127
128 return ret;
129
130#else
131 return ::system (cmd_str.c_str ());
132#endif
133}
134
135std::string
137{
138 std::string retval;
139
140#if defined (OCTAVE_USE_WINDOWS_API)
141 wchar_t *tmp = _wgetcwd (nullptr, 0);
142
143 if (! tmp)
144 (*current_liboctave_error_handler) ("unable to find current directory");
145
146 std::wstring tmp_wstr (tmp);
147 free (tmp);
148
149 std::string tmp_str = u8_from_wstring (tmp_wstr);
150
151 retval = tmp_str;
152
153#else
154 // Using octave_getcwd_wrapper ensures that we have a getcwd that
155 // will allocate a buffer as large as necessary if buf and size are
156 // both 0.
157
158 char *tmp = octave_getcwd_wrapper (nullptr, 0);
159
160 if (! tmp)
161 (*current_liboctave_error_handler) ("unable to find current directory");
162
163 retval = tmp;
164 free (tmp);
165#endif
166
167 return retval;
168}
169
170int
171chdir (const std::string& path_arg)
172{
173 std::string path = sys::file_ops::tilde_expand (path_arg);
174
175#if defined (OCTAVE_USE_WINDOWS_API)
176 if (path.length () == 2 && path[1] == ':')
177 path += '\\';
178#endif
179
180 return octave_chdir_wrapper (path.c_str ());
181}
182
183bool
184get_dirlist (const std::string& dirname, string_vector& dirlist,
185 std::string& msg)
186{
187 dirlist = "";
188 msg = "";
189#if defined (OCTAVE_USE_WINDOWS_API)
190 _WIN32_FIND_DATAW ffd;
191
192 std::string path_name (dirname);
193 if (path_name.empty ())
194 return true;
195
196 if (path_name.back () == '\\' || path_name.back () == '/')
197 path_name.push_back ('*');
198 else
199 path_name.append (R"(\*)");
200
201 // Find first file in directory.
202 std::wstring wpath_name = u8_to_wstring (path_name);
203 HANDLE hFind = FindFirstFileW (wpath_name.c_str (), &ffd);
204 if (INVALID_HANDLE_VALUE == hFind)
205 {
206 DWORD errCode = GetLastError ();
207 char *errorText = nullptr;
208 FormatMessageA (FORMAT_MESSAGE_FROM_SYSTEM |
209 FORMAT_MESSAGE_ALLOCATE_BUFFER |
210 FORMAT_MESSAGE_IGNORE_INSERTS,
211 nullptr, errCode,
212 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
213 reinterpret_cast<char *> (&errorText), 0, nullptr);
214 if (errorText != nullptr)
215 {
216 msg = std::string (errorText);
217 LocalFree (errorText);
218 }
219 return false;
220 }
221
222 std::list<std::string> dirlist_str;
223 do
224 dirlist_str.push_back (u8_from_wstring (ffd.cFileName));
225 while (FindNextFileW (hFind, &ffd) != 0);
226
227 FindClose(hFind);
228
229 dirlist = string_vector (dirlist_str);
230
231#else
232
233 dir_entry dir (dirname);
234
235 if (! dir)
236 {
237 msg = dir.error ();
238 return false;
239 }
240
241 dirlist = dir.read ();
242
243 dir.close ();
244#endif
245
246 return true;
247}
248
249#if defined (OCTAVE_USE_WINDOWS_API)
250
251static bool
252check_fseek_ftell_workaround_needed (bool set_nonbuffered_mode)
253{
254 // To check whether the workaround is needed:
255 //
256 // * Create a tmp file with LF line endings only.
257 //
258 // * Open that file for reading in text mode.
259 //
260 // * Read a line.
261 //
262 // * Use ftello to record the position of the beginning of the
263 // second line.
264 //
265 // * Read and save the contents of the second line.
266 //
267 // * Use fseeko to return to the saved position.
268 //
269 // * Read the second line again and compare to the previously
270 // saved text.
271 //
272 // * If the lines are different, we need to set non-buffered
273 // input mode for files opened in text mode.
274
275 std::string tmpname = sys::tempnam ("", "oct-");
276
277 if (tmpname.empty ())
278 {
279 (*current_liboctave_warning_handler)
280 ("fseek/ftell bug check failed (tmp name creation)!");
281 return false;
282 }
283
284 std::FILE *fptr = std::fopen (tmpname.c_str (), "wb");
285
286 if (! fptr)
287 {
288 (*current_liboctave_warning_handler)
289 ("fseek/ftell bug check failed (opening tmp file for writing)!");
290 return false;
291 }
292
293 fprintf (fptr, "%s", "foo\nbar\nbaz\n");
294
295 std::fclose (fptr);
296
297 fptr = std::fopen (tmpname.c_str (), "rt");
298
299 if (! fptr)
300 {
301 (*current_liboctave_warning_handler)
302 ("fseek/ftell bug check failed (opening tmp file for reading)!");
303 return false;
304 }
305
306 unwind_action act ([fptr, tmpname] ()
307 {
308 std::fclose (fptr);
309 sys::unlink (tmpname);
310 });
311
312 if (set_nonbuffered_mode)
313 ::setvbuf (fptr, nullptr, _IONBF, 0);
314
315 while (true)
316 {
317 int c = fgetc (fptr);
318
319 if (c == EOF)
320 {
321 (*current_liboctave_warning_handler)
322 ("fseek/ftell bug check failed (skipping first line)!");
323 return false;
324 }
325
326 if (c == '\n')
327 break;
328 }
329
330 off_t pos = octave_ftello_wrapper (fptr);
331
332 char buf1[8];
333 int i = 0;
334 while (true)
335 {
336 int c = fgetc (fptr);
337
338 if (c == EOF)
339 {
340 (*current_liboctave_warning_handler)
341 ("fseek/ftell bug check failed (reading second line)!");
342 return false;
343 }
344
345 if (c == '\n')
346 break;
347
348 buf1[i++] = static_cast<char> (c);
349 }
350 buf1[i] = '\0';
351
353
354 char buf2[8];
355 i = 0;
356 while (true)
357 {
358 int c = fgetc (fptr);
359
360 if (c == EOF)
361 {
362 (*current_liboctave_warning_handler)
363 ("fseek/ftell bug check failed (reading after repositioning)!");
364 return false;
365 }
366
367 if (c == '\n')
368 break;
369
370 buf2[i++] = static_cast<char> (c);
371 }
372 buf2[i] = '\0';
373
374 return strcmp (buf1, buf2);
375}
376
377static std::string
378get_formatted_last_error ()
379{
380 std::string msg = "";
381
382 DWORD last_error = GetLastError ();
383
384 wchar_t *error_text = nullptr;
385 FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM |
386 FORMAT_MESSAGE_ALLOCATE_BUFFER |
387 FORMAT_MESSAGE_IGNORE_INSERTS,
388 nullptr, last_error,
389 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
390 reinterpret_cast<wchar_t *> (&error_text), 0, nullptr);
391
392 if (error_text != nullptr)
393 {
394 msg = u8_from_wstring (error_text);
395 LocalFree (error_text);
396 }
397 else
398 msg = "Unknown error.";
399
400 return msg;
401}
402#endif
403
404bool
405file_exists (const std::string& filename, bool is_dir)
406{
407 // Check if a file with the given name exists on the file system. If is_dir
408 // is true (the default), also return true if filename refers to a directory.
409#if defined (OCTAVE_USE_WINDOWS_API)
410 std::wstring w_fn = u8_to_wstring (filename);
411
412 DWORD f_attr = GetFileAttributesW (w_fn.c_str ());
413
414 return ((f_attr != INVALID_FILE_ATTRIBUTES)
415 && (is_dir || ! (f_attr & FILE_ATTRIBUTE_DIRECTORY)));
416
417#else
418 file_stat fs (filename);
419
420 return (fs && (is_dir || ! fs.is_dir ()));
421
422#endif
423}
424
425bool
426file_exists (const std::string& filename, bool is_dir, std::string& msg)
427{
428 // Check if a file with the given name exists on the file system. If is_dir
429 // is true (the default), also return true if filename refers to a directory.
430#if defined (OCTAVE_USE_WINDOWS_API)
431 std::wstring w_fn = u8_to_wstring (filename);
432
433 DWORD f_attr = GetFileAttributesW (w_fn.c_str ());
434
435 if (f_attr == INVALID_FILE_ATTRIBUTES)
436 msg = get_formatted_last_error ();
437
438 return ((f_attr != INVALID_FILE_ATTRIBUTES)
439 && (is_dir || ! (f_attr & FILE_ATTRIBUTE_DIRECTORY)));
440
441#else
442 file_stat fs (filename);
443
444 if (! fs)
445 msg = fs.error ();
446
447 return (fs && (is_dir || ! fs.is_dir ()));
448
449#endif
450}
451
452bool
453dir_exists (const std::string& dirname)
454{
455 // Check if a directory with the given name exists on the file system.
456#if defined (OCTAVE_USE_WINDOWS_API)
457 std::wstring w_dn = u8_to_wstring (dirname);
458
459 DWORD f_attr = GetFileAttributesW (w_dn.c_str ());
460
461 return ((f_attr != INVALID_FILE_ATTRIBUTES)
462 && (f_attr & FILE_ATTRIBUTE_DIRECTORY));
463
464#else
465 file_stat fs (dirname);
466
467 return (fs && fs.is_dir ());
468
469#endif
470}
471
472bool
473dir_exists (const std::string& dirname, std::string& msg)
474{
475 // Check if a directory with the given name exists on the file system.
476#if defined (OCTAVE_USE_WINDOWS_API)
477 std::wstring w_dn = u8_to_wstring (dirname);
478
479 DWORD f_attr = GetFileAttributesW (w_dn.c_str ());
480
481 if (f_attr == INVALID_FILE_ATTRIBUTES)
482 msg = get_formatted_last_error ();
483
484 return ((f_attr != INVALID_FILE_ATTRIBUTES)
485 && (f_attr & FILE_ATTRIBUTE_DIRECTORY));
486
487#else
488 file_stat fs (dirname);
489
490 if (! fs)
491 msg = fs.error ();
492
493 return (fs && fs.is_dir ());
494
495#endif
496}
497
498// Return TRUE if FILE1 and FILE2 refer to the same (physical) file.
499
500bool
501same_file (const std::string& file1, const std::string& file2)
502{
503#if defined (OCTAVE_USE_WINDOWS_API)
504
505 // FIXME: When Octave switches to C++17, consider replacing this function
506 // by https://en.cppreference.com/w/cpp/filesystem/equivalent.
507
508 bool retval = false;
509
510 std::wstring file1w = sys::u8_to_wstring (file1);
511 std::wstring file2w = sys::u8_to_wstring (file2);
512 const wchar_t *f1 = file1w.c_str ();
513 const wchar_t *f2 = file2w.c_str ();
514
515 bool f1_is_dir = GetFileAttributesW (f1) & FILE_ATTRIBUTE_DIRECTORY;
516 bool f2_is_dir = GetFileAttributesW (f2) & FILE_ATTRIBUTE_DIRECTORY;
517
518 // Windows native code
519 // Reference: http://msdn2.microsoft.com/en-us/library/aa363788.aspx
520
521 DWORD share = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;
522
523 HANDLE hfile1
524 = CreateFileW (f1, 0, share, 0, OPEN_EXISTING,
525 f1_is_dir ? FILE_FLAG_BACKUP_SEMANTICS : 0, 0);
526
527 if (hfile1 != INVALID_HANDLE_VALUE)
528 {
529 HANDLE hfile2
530 = CreateFileW (f2, 0, share, 0, OPEN_EXISTING,
531 f2_is_dir ? FILE_FLAG_BACKUP_SEMANTICS : 0, 0);
532
533 if (hfile2 != INVALID_HANDLE_VALUE)
534 {
535 BY_HANDLE_FILE_INFORMATION hfi1;
536 BY_HANDLE_FILE_INFORMATION hfi2;
537
538 if (GetFileInformationByHandle (hfile1, &hfi1)
539 && GetFileInformationByHandle (hfile2, &hfi2))
540 {
541 retval = (hfi1.dwVolumeSerialNumber == hfi2.dwVolumeSerialNumber
542 && hfi1.nFileIndexHigh == hfi2.nFileIndexHigh
543 && hfi1.nFileIndexLow == hfi2.nFileIndexLow
544 && hfi1.nFileSizeHigh == hfi2.nFileSizeHigh
545 && hfi1.nFileSizeLow == hfi2.nFileSizeLow
546 && hfi1.ftLastWriteTime.dwLowDateTime
547 == hfi2.ftLastWriteTime.dwLowDateTime
548 && hfi1.ftLastWriteTime.dwHighDateTime
549 == hfi2.ftLastWriteTime.dwHighDateTime);
550 }
551
552 CloseHandle (hfile2);
553 }
554
555 CloseHandle (hfile1);
556 }
557
558 return retval;
559
560#else
561
562 // POSIX Code
563
564 sys::file_stat fs_file1 (file1);
565 sys::file_stat fs_file2 (file2);
566
567 return (fs_file1 && fs_file2
568 && fs_file1.ino () == fs_file2.ino ()
569 && fs_file1.dev () == fs_file2.dev ());
570
571#endif
572}
573
574std::FILE *
575fopen (const std::string& filename, const std::string& mode)
576{
577#if defined (OCTAVE_USE_WINDOWS_API)
578
579 std::wstring wfilename = u8_to_wstring (filename);
580 std::wstring wmode = u8_to_wstring (mode);
581
582 std::FILE *fptr = _wfopen (wfilename.c_str (), wmode.c_str ());
583
584 static bool fseek_ftell_bug_workaround_needed = false;
585 static bool fseek_ftell_bug_checked = false;
586
587 if (! fseek_ftell_bug_checked && mode.find ('t') != std::string::npos)
588 {
589 // FIXME: Is the following workaround needed for all files
590 // opened in text mode, or only for files opened for reading?
591
592 // Try to avoid fseek/ftell bug on Windows systems by setting
593 // non-buffered input mode for files opened in text mode, but
594 // only if it appears that the workaround is needed. See
595 // Octave bug #58055.
596
597 // To check whether the workaround is needed:
598 //
599 // * Create a tmp file with LF line endings only.
600 //
601 // * Open that file for reading in text mode.
602 //
603 // * Read a line.
604 //
605 // * Use ftello to record the position of the beginning of
606 // the second line.
607 //
608 // * Read and save the contents of the second line.
609 //
610 // * Use fseeko to return to the saved position.
611 //
612 // * Read the second line again and compare to the
613 // previously saved text.
614 //
615 // * If the lines are different, we need to set non-buffered
616 // input mode for files opened in text mode.
617 //
618 // * To verify that the workaround solves the problem,
619 // repeat the above test with non-buffered input mode. If
620 // that fails, warn that there may be trouble with
621 // ftell/fseek when reading files opened in text mode.
622
623 if (check_fseek_ftell_workaround_needed (false))
624 {
625 if (check_fseek_ftell_workaround_needed (true))
626 (*current_liboctave_warning_handler)
627 ("fseek/ftell may fail for files opened in text mode");
628 else
629 fseek_ftell_bug_workaround_needed = true;
630 }
631
632 fseek_ftell_bug_checked = true;
633 }
634
635 if (fseek_ftell_bug_workaround_needed
636 && mode.find ('t') != std::string::npos)
637 ::setvbuf (fptr, nullptr, _IONBF, 0);
638
639 return fptr;
640
641#else
642 return std::fopen (filename.c_str (), mode.c_str ());
643#endif
644}
645
646std::FILE *
647fopen_tmp (const std::string& name, const std::string& mode)
648{
649#if defined (OCTAVE_USE_WINDOWS_API)
650
651 // Append "D" to the mode string to indicate that this is a temporary
652 // file that should be deleted when the last open handle is closed.
653 std::string tmp_mode = mode + "D";
654
655 return std::fopen (name.c_str (), tmp_mode.c_str ());
656
657#else
658
659 std::FILE *fptr = std::fopen (name.c_str (), mode.c_str ());
660
661 // From gnulib: This relies on the Unix semantics that a file is not
662 // really removed until it is closed.
663 octave_unlink_wrapper (name.c_str ());
664
665 return fptr;
666
667#endif
668}
669
670std::fstream
671fstream (const std::string& filename, const std::ios::openmode mode)
672{
673#if defined (OCTAVE_USE_WINDOWS_API)
674
675 std::wstring wfilename = u8_to_wstring (filename);
676
677 return std::fstream (wfilename.c_str (), mode);
678
679#else
680 return std::fstream (filename.c_str (), mode);
681#endif
682}
683
684std::ifstream
685ifstream (const std::string& filename, const std::ios::openmode mode)
686{
687#if defined (OCTAVE_USE_WINDOWS_API)
688
689 std::wstring wfilename = u8_to_wstring (filename);
690
691 return std::ifstream (wfilename.c_str (), mode);
692
693#else
694 return std::ifstream (filename.c_str (), mode);
695#endif
696}
697
698std::ofstream
699ofstream (const std::string& filename, const std::ios::openmode mode)
700{
701#if defined (OCTAVE_USE_WINDOWS_API)
702
703 std::wstring wfilename = u8_to_wstring (filename);
704
705 return std::ofstream (wfilename.c_str (), mode);
706
707#else
708 return std::ofstream (filename.c_str (), mode);
709#endif
710}
711
712void
713putenv_wrapper (const std::string& name, const std::string& value)
714{
715 // Short of extreme measures to track memory, altering the environment
716 // always leaks memory, but the saving grace is that the leaks are small.
717
718#if defined (OCTAVE_USE_WINDOWS_API)
719 // FIXME: The malloc leaks memory, but so would a call to setenv.
720
721 // As far as I can see there's no way to distinguish between the
722 // various errors; putenv doesn't have errno values.
723
724 if (name.find ('=') != std::string::npos)
725 (*current_liboctave_error_handler)
726 ("putenv: name (%s) must not contain '='", name.c_str());
727
728 std::string new_env = name + "=" + value;
729
730 std::wstring new_wenv = u8_to_wstring (new_env);
731
732 int len = (new_wenv.length () + 1) * sizeof (wchar_t);
733
734 wchar_t *new_item = static_cast<wchar_t *> (std::malloc (len));
735
736 wcscpy (new_item, new_wenv.c_str());
737
738 if (_wputenv (new_item) < 0)
739 (*current_liboctave_error_handler)
740 ("putenv (%s) failed", new_env.c_str());
741#else
742 // FIXME: Using setenv leaks memory, but so would using malloc and putenv.
743
744 if (octave_setenv_wrapper (name.c_str (), value.c_str (), 1) < 0)
746 ("setenv (%s, %s) failed with error %d", name.c_str (), value.c_str (),
747 errno);
748#endif
749}
750
751std::string
752getenv_wrapper (const std::string& name)
753{
754#if defined (OCTAVE_USE_WINDOWS_API)
755 std::wstring wname = u8_to_wstring (name);
756 wchar_t *env = _wgetenv (wname.c_str ());
757 return env ? u8_from_wstring (env) : "";
758#else
759 char *env = ::getenv (name.c_str ());
760 return env ? env : "";
761#endif
762}
763
764int
765unsetenv_wrapper (const std::string& name)
766{
767#if defined (OCTAVE_USE_WINDOWS_API)
768 putenv_wrapper (name, "");
769
770 // Also remove variable from environment.
771 std::wstring wname = u8_to_wstring (name);
772 return (SetEnvironmentVariableW (wname.c_str (), nullptr) ? 0 : -1);
773#else
774 return octave_unsetenv_wrapper (name.c_str ());
775#endif
776}
777
778bool
779isenv_wrapper (const std::string& name)
780{
781#if defined (OCTAVE_USE_WINDOWS_API)
782 std::wstring wname = u8_to_wstring (name);
783 wchar_t *env = _wgetenv (wname.c_str ());
784#else
785 char *env = ::getenv (name.c_str ());
786#endif
787 return env != 0;
788}
789
790std::wstring
791u8_to_wstring (const std::string& utf8_string)
792{
793 // convert multibyte UTF-8 string to wide character string
794 size_t srclen = utf8_string.length ();
795 const uint8_t *src = reinterpret_cast<const uint8_t *> (utf8_string.c_str ());
796
797 size_t length = 0;
798 char *wchar = octave_u8_conv_to_encoding ("wchar_t", src, srclen, &length);
799
800 if (! wchar)
801 return std::wstring ();
802
803 // memcpy to std::wstring to avoid potential memory alignment issues
804 std::wstring retval;
805 retval.resize (length / sizeof (wchar_t));
806 std::memcpy (retval.data (), wchar, length);
807 free (static_cast<void *> (wchar));
808
809 return retval;
810}
811
812std::string
813u8_from_wstring (const std::wstring& wchar_string)
814{
815 // convert wide character string to multibyte UTF-8 string
816 size_t srclen = wchar_string.length () * sizeof (wchar_t);
817 const char *src = reinterpret_cast<const char *> (wchar_string.c_str ());
818
819 size_t length = 0;
820 char *mbchar = reinterpret_cast<char *>
821 (octave_u8_conv_from_encoding ("wchar_t", src, srclen, &length));
822
823 std::string retval = "";
824 if (mbchar != nullptr)
825 {
826 retval = std::string (mbchar, length);
827 free (static_cast<void *> (mbchar));
828 }
829
830 return retval;
831}
832
833// At quite a few places in the code we are passing file names as
834// char arrays to external library functions.
835
836// When these functions try to locate the corresponding file on the
837// disc, they need to use the wide character API on Windows to
838// correctly open files with non-ASCII characters.
839
840// But they have no way of knowing which encoding we are using for
841// the passed string. So they have no way of reliably converting to
842// a wchar_t array. (I.e. there is no possible fix for these
843// functions with current C or C++.)
844
845// To solve the dilemma, the function "get_ASCII_filename" first
846// checks whether there are any non-ASCII characters in the passed
847// file name. If there are not, it returns the original name.
848
849// Otherwise, it optionally tries to convert the file name to the locale
850// charset.
851
852// If the file name contains characters that cannot be converted to the
853// locale charset (or that step is skipped), it tries to obtain the short
854// file name (8.3 naming scheme) which only consists of ASCII characters
855// and are safe to pass. However, short file names can be disabled for
856// performance reasons on the file system level with NTFS and they are not
857// stored on other file systems (e.g. ExFAT). So there is no guarantee
858// that these exist.
859
860// If short file names are not stored, a hard link to the file is
861// created. For this the path to the file is split at the deepest
862// possible level that doesn't contain non-ASCII characters. At
863// that level a hidden folder is created that holds the hard links.
864// That means we need to have write access on that location. A path
865// to that hard link is returned.
866
867// If the file system is FAT32, there are no hard links. But FAT32
868// always stores short file names. So we are safe.
869
870// ExFAT that is occasionally used on USB sticks and SD cards stores
871// neither short file names nor does it support hard links. So for
872// exFAT with this function, there is (currently) no way to generate
873// a file name that is stripped from non-ASCII characters but still
874// is valid.
875
876// For Unixy systems, this function does nothing.
877
878std::string
879get_ASCII_filename (const std::string& orig_file_name,
880 const bool allow_locale)
881{
882#if defined (OCTAVE_USE_WINDOWS_API)
883
884 // Return file name that only contains ASCII characters that can
885 // be used to access the file orig_file_name. The original file
886 // must exist in the file system before calling this function.
887 // This is useful for passing file names to functions that are not
888 // aware of the character encoding we are using.
889
890 // 0. Check whether filename contains non-ASCII (UTF-8) characters.
891
892 std::string::const_iterator first_non_ASCII
893 = std::find_if (orig_file_name.begin (), orig_file_name.end (),
894 [](char c) { return (c < 0 || c >= 128); });
895
896 if (first_non_ASCII == orig_file_name.end ())
897 return orig_file_name;
898
899 // 1. Optionally, check if all characters in the path can be successfully
900 // converted to the locale charset
901 if (allow_locale)
902 {
903 const char *locale = octave_locale_charset_wrapper ();
904 if (locale)
905 {
906 const uint8_t *name_u8 = reinterpret_cast<const uint8_t *>
907 (orig_file_name.c_str ());
908 std::size_t length = 0;
909 char *name_locale = octave_u8_conv_to_encoding_strict
910 (locale, name_u8,
911 orig_file_name.length () + 1, &length);
912 if (name_locale)
913 {
914 std::string file_name_locale (name_locale, length);
915 free (name_locale);
916 return file_name_locale;
917 }
918 }
919 }
920
921 // 2. Check if file system stores short filenames (might be ASCII-only).
922
923 std::wstring w_orig_file_name_str = u8_to_wstring (orig_file_name);
924 const wchar_t *w_orig_file_name = w_orig_file_name_str.c_str ();
925
926 // Get full path to file
927 wchar_t w_full_file_name[_MAX_PATH];
928 if (_wfullpath (w_full_file_name, w_orig_file_name, _MAX_PATH) == nullptr)
929 return orig_file_name;
930
931 std::wstring w_full_file_name_str = w_full_file_name;
932
933 // Get short filename (8.3) from UTF-16 filename.
934
935 long length = GetShortPathNameW (w_full_file_name, nullptr, 0);
936
937 if (length > 0)
938 {
939 // Dynamically allocate the correct size (terminating null char
940 // was included in length).
941
942 OCTAVE_LOCAL_BUFFER (wchar_t, w_short_file_name, length);
943 GetShortPathNameW (w_full_file_name, w_short_file_name, length);
944
945 std::wstring w_short_file_name_str
946 = std::wstring (w_short_file_name, length);
947
948 if (w_short_file_name_str.compare (0, length-1, w_full_file_name_str) != 0)
949 {
950 // Check whether short file name contains non-ASCII characters
951 std::string short_file_name
952 = u8_from_wstring (w_short_file_name_str);
953 first_non_ASCII
954 = std::find_if (short_file_name.begin (),
955 short_file_name.end (),
956 [](char c) { return (c < 0 || c >= 128); });
957 if (first_non_ASCII == short_file_name.end ())
958 return short_file_name;
959 }
960 }
961
962 // 3. Create hard link with only-ASCII characters.
963 // Get longest possible part of path that only contains ASCII chars.
964
965 std::wstring::iterator w_first_non_ASCII
966 = std::find_if (w_full_file_name_str.begin (), w_full_file_name_str.end (),
967 [](wchar_t c) { return (c < 0 || c >= 128); });
968 std::wstring tmp_substr
969 = std::wstring (w_full_file_name_str.begin (), w_first_non_ASCII);
970
971 std::size_t pos
972 = tmp_substr.find_last_of (u8_to_wstring (file_ops::dir_sep_chars ()));
973
974 std::string par_dir
975 = u8_from_wstring (w_full_file_name_str.substr (0, pos+1));
976
977 // Create .oct_ascii directory.
978 // FIXME: We need to have write permission in this location.
979
980 std::string oct_ascii_dir = par_dir + ".oct_ascii";
981 std::string test_dir = canonicalize_file_name (oct_ascii_dir);
982
983 if (test_dir.empty ())
984 {
985 std::string msg;
986 int status = sys::mkdir (oct_ascii_dir, 0777, msg);
987
988 if (status < 0)
989 return orig_file_name;
990
991 // Set hidden property.
992 SetFileAttributesA (oct_ascii_dir.c_str (), FILE_ATTRIBUTE_HIDDEN);
993 }
994
995 // Create file from hash of full filename.
996 std::string filename_hash
997 = (oct_ascii_dir + file_ops::dir_sep_str ()
998 + crypto::hash ("SHA1", orig_file_name));
999
1000 // FIXME: This is just to check if the file exists. Use a more efficient
1001 // method.
1002 std::string abs_filename_hash = canonicalize_file_name (filename_hash);
1003
1004 if (! abs_filename_hash.empty ())
1005 sys::unlink (filename_hash);
1006
1007 // At this point, we know that we have only ASCII characters.
1008 // So instead of converting, just copy the characters to std::wstring.
1009 std::wstring w_filename_hash (filename_hash.begin (),
1010 filename_hash.end ());
1011
1012 if (CreateHardLinkW (w_filename_hash.c_str (), w_orig_file_name, nullptr))
1013 return filename_hash;
1014
1015#else
1016
1017 octave_unused_parameter (allow_locale);
1018
1019#endif
1020
1021 return orig_file_name;
1022}
1023
1024OCTAVE_END_NAMESPACE(sys)
1025OCTAVE_END_NAMESPACE(octave)
#define SEEK_SET
bool is_dir() const
Definition file-stat.cc:64
std::string error() const
Definition file-stat.h:146
Definition dir-ops.h:39
string_vector read()
Definition dir-ops.cc:90
std::string error() const
Definition dir-ops.h:85
bool close()
Definition dir-ops.cc:129
Definition oct-env.h:37
OCTAVE_BEGIN_NAMESPACE(octave) static octave_value daspk_fcn
std::string canonicalize_file_name(const std::string &name)
Definition file-ops.cc:868
std::string dirname(const std::string &path)
Definition file-ops.cc:369
int octave_fseeko_wrapper(FILE *fp, off_t offset, int whence)
off_t octave_ftello_wrapper(FILE *fp)
OCTAVE_NORETURN liboctave_error_handler current_liboctave_error_handler
Definition lo-error.c:41
const char * octave_locale_charset_wrapper(void)
#define OCTAVE_LOCAL_BUFFER(T, buf, size)
Definition oct-locbuf.h:44
FloatComplex(* fptr)(const FloatComplex &, float, int, octave_idx_type &)
bool strcmp(const T &str_a, const T &str_b)
Octave string utility functions.
int system(const std::string &cmd_str)
Definition oct-sysdep.cc:63
std::FILE * fopen(const std::string &filename, const std::string &mode)
bool dir_exists(const std::string &dirname)
std::FILE * fopen_tmp(const std::string &name, const std::string &mode)
std::string u8_from_wstring(const std::wstring &wchar_string)
std::string get_ASCII_filename(const std::string &orig_file_name, const bool allow_locale)
std::string getenv_wrapper(const std::string &name)
bool file_exists(const std::string &filename, bool is_dir)
bool isenv_wrapper(const std::string &name)
std::ofstream ofstream(const std::string &filename, const std::ios::openmode mode)
int chdir(const std::string &path_arg)
std::string getcwd()
std::ifstream ifstream(const std::string &filename, const std::ios::openmode mode)
std::wstring u8_to_wstring(const std::string &utf8_string)
void putenv_wrapper(const std::string &name, const std::string &value)
bool get_dirlist(const std::string &dirname, string_vector &dirlist, std::string &msg)
bool same_file(const std::string &file1, const std::string &file2)
int unsetenv_wrapper(const std::string &name)
void free(void *)
int octave_setenv_wrapper(const char *envname, const char *envval, int overwrite)
char * octave_u8_conv_to_encoding_strict(const char *tocode, const uint8_t *src, size_t srclen, size_t *lengthp)
char * octave_u8_conv_to_encoding(const char *tocode, const uint8_t *src, size_t srclen, size_t *lengthp)
uint8_t * octave_u8_conv_from_encoding(const char *fromcode, const char *src, size_t srclen, size_t *lengthp)
char * octave_getcwd_wrapper(char *nm, size_t len)
int octave_unlink_wrapper(const char *nm)
int octave_chdir_wrapper(const char *nm)
int octave_unsetenv_wrapper(const char *name)
F77_RET_T len
Definition xerbla.cc:61