Blender V4.5
storage.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
10
11#include <cstdio>
12#include <cstdlib>
13#include <sys/types.h>
14
15#include <sys/stat.h>
16
17#if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__HAIKU__)
18/* Other modern unix OS's should probably use this also. */
19# include <sys/statvfs.h>
20# define USE_STATFS_STATVFS
21#endif
22
23#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || \
24 defined(__DragonFly__)
25/* For statfs */
26# include <sys/mount.h>
27# include <sys/param.h>
28#endif
29
30#if defined(__linux__) || defined(__hpux) || defined(__GNU__) || defined(__GLIBC__)
31# include <sys/vfs.h>
32#endif
33
34#include <cstring>
35#include <fcntl.h>
36
37#ifdef WIN32
38# include "BLI_string_utf8.h"
39# include "BLI_winstuff.h"
40# include "utfconv.hh"
41# include <ShObjIdl.h>
42# include <direct.h>
43# include <io.h>
44# include <stdbool.h>
45#else
46# include <pwd.h>
47# include <sys/ioctl.h>
48# include <unistd.h>
49#endif
50
51/* lib includes */
52#include "MEM_guardedalloc.h"
53
54#include "BLI_fileops.h"
55#include "BLI_linklist.h"
56#include "BLI_path_utils.hh"
57#include "BLI_string.h"
58#include "BLI_threads.h"
59#include "BLI_utildefines.h"
60
61/* NOTE: The implementation for Apple lives in storage_apple.mm. */
62#if !defined(__APPLE__)
63bool BLI_change_working_dir(const char *dir)
64{
66
67 if (!BLI_is_dir(dir)) {
68 return false;
69 }
70# if defined(WIN32)
71 wchar_t wdir[FILE_MAX];
72 if (conv_utf_8_to_16(dir, wdir, ARRAY_SIZE(wdir)) != 0) {
73 return false;
74 }
75 return _wchdir(wdir) == 0;
76# else
77 int result = chdir(dir);
78 if (result == 0) {
79 BLI_setenv("PWD", dir);
80 }
81 return result == 0;
82# endif
83}
84
85char *BLI_current_working_dir(char *dir, const size_t maxncpy)
86{
87# if defined(WIN32)
88 wchar_t path[MAX_PATH];
89 if (_wgetcwd(path, MAX_PATH)) {
90 if (BLI_strncpy_wchar_as_utf8(dir, path, maxncpy) != maxncpy) {
91 return dir;
92 }
93 }
94 return nullptr;
95# else
96 const char *pwd = BLI_getenv("PWD");
97 if (pwd) {
98 size_t srclen = BLI_strnlen(pwd, maxncpy);
99 if (srclen != maxncpy) {
100 memcpy(dir, pwd, srclen + 1);
101 return dir;
102 }
103 return nullptr;
104 }
105 return getcwd(dir, maxncpy);
106# endif
107}
108#endif /* !defined (__APPLE__) */
109
110const char *BLI_dir_home()
111{
112 const char *home_dir;
113
114#ifdef WIN32
115 home_dir = BLI_getenv("userprofile");
116#else
117 /* Return the users home directory with a fallback when the environment variable isn't set.
118 * Failure to access `$HOME` is rare but possible, see: #2931.
119 *
120 * Any errors accessing home is likely caused by a broken/unsupported configuration,
121 * nevertheless, failing to null check would crash which makes the error difficult
122 * for users troubleshoot. */
123 home_dir = BLI_getenv("HOME");
124 if (home_dir == nullptr) {
125 if (const passwd *pwuser = getpwuid(getuid())) {
126 home_dir = pwuser->pw_dir;
127 }
128 }
129#endif
130
131 return home_dir;
132}
133
134double BLI_dir_free_space(const char *dir)
135{
136#ifdef WIN32
137 DWORD sectorspc, bytesps, freec, clusters;
138 char tmp[4];
139
140 tmp[0] = '\\';
141 tmp[1] = 0; /* Just a fail-safe. */
142 if (ELEM(dir[0], '/', '\\')) {
143 tmp[0] = '\\';
144 tmp[1] = 0;
145 }
146 else if (dir[1] == ':') {
147 tmp[0] = dir[0];
148 tmp[1] = ':';
149 tmp[2] = '\\';
150 tmp[3] = 0;
151 }
152
153 GetDiskFreeSpace(tmp, &sectorspc, &bytesps, &freec, &clusters);
154
155 return double(freec * bytesps * sectorspc);
156#else
157
158# ifdef USE_STATFS_STATVFS
159 struct statvfs disk;
160# else
161 struct statfs disk;
162# endif
163
164 char dirname[FILE_MAXDIR], *slash;
165 int len = strlen(dir);
166
167 if (len >= FILE_MAXDIR) {
168 /* path too long */
169 return -1;
170 }
171
172 memcpy(dirname, dir, len + 1);
173
174 if (len) {
175 slash = strrchr(dirname, '/');
176 if (slash) {
177 slash[1] = '\0';
178 }
179 }
180 else {
181 dirname[0] = '/';
182 dirname[1] = '\0';
183 }
184
185# if defined(USE_STATFS_STATVFS)
186 if (statvfs(dirname, &disk)) {
187 return -1;
188 }
189# elif defined(USE_STATFS_4ARGS)
190 if (statfs(dirname, &disk, sizeof(struct statfs), 0)) {
191 return -1;
192 }
193# else
194 if (statfs(dirname, &disk)) {
195 return -1;
196 }
197# endif
198
199 return double(disk.f_bsize) * double(disk.f_bfree);
200#endif
201}
202
203int64_t BLI_ftell(FILE *stream)
204{
205#ifdef WIN32
206 return _ftelli64(stream);
207#else
208 return ftell(stream);
209#endif
210}
211
212int BLI_fseek(FILE *stream, int64_t offset, int whence)
213{
214#ifdef WIN32
215 return _fseeki64(stream, offset, whence);
216#else
217 return fseek(stream, offset, whence);
218#endif
219}
220
221int64_t BLI_lseek(int fd, int64_t offset, int whence)
222{
223#ifdef WIN32
224 return _lseeki64(fd, offset, whence);
225#else
226 return lseek(fd, offset, whence);
227#endif
228}
229
231{
232 BLI_stat_t st;
233 if ((file < 0) || (BLI_fstat(file, &st) == -1)) {
234 return -1;
235 }
236 return st.st_size;
237}
238
239size_t BLI_file_size(const char *path)
240{
241 BLI_stat_t stats;
242 if (BLI_stat(path, &stats) == -1) {
243 return -1;
244 }
245 return stats.st_size;
246}
247
248/* Return file attributes. Apple version of this function is defined in storage_apple.mm */
249#ifndef __APPLE__
251{
252 int ret = 0;
253
254# ifdef WIN32
255
256 if (BLI_path_extension_check(path, ".lnk")) {
257 return FILE_ATTR_ALIAS;
258 }
259
260 WCHAR wline[FILE_MAXDIR];
261 if (conv_utf_8_to_16(path, wline, ARRAY_SIZE(wline)) != 0) {
262 return eFileAttributes(ret);
263 }
264
265 DWORD attr = GetFileAttributesW(wline);
266 if (attr == INVALID_FILE_ATTRIBUTES) {
267 BLI_assert_msg(GetLastError() != ERROR_FILE_NOT_FOUND,
268 "BLI_file_attributes should only be called on existing files.");
269 return eFileAttributes(ret);
270 }
271
272 if (attr & FILE_ATTRIBUTE_READONLY) {
274 }
275 if (attr & FILE_ATTRIBUTE_HIDDEN) {
277 }
278 if (attr & FILE_ATTRIBUTE_SYSTEM) {
280 }
281 if (attr & FILE_ATTRIBUTE_ARCHIVE) {
283 }
284 if (attr & FILE_ATTRIBUTE_COMPRESSED) {
286 }
287 if (attr & FILE_ATTRIBUTE_ENCRYPTED) {
289 }
290 if (attr & FILE_ATTRIBUTE_TEMPORARY) {
292 }
293 if (attr & FILE_ATTRIBUTE_SPARSE_FILE) {
295 }
296 if (attr & FILE_ATTRIBUTE_OFFLINE || attr & FILE_ATTRIBUTE_RECALL_ON_OPEN ||
297 attr & FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS)
298 {
300 }
301 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
303 }
304
305# else
306
307 UNUSED_VARS(path);
308
309 /* TODO:
310 * If Immutable set FILE_ATTR_READONLY
311 * If Archived set FILE_ATTR_ARCHIVE
312 */
313# endif
314 return eFileAttributes(ret);
315}
316#endif
317
318#ifndef __APPLE__ /* Apple version is defined in `storage_apple.mm`. */
319bool BLI_file_alias_target(const char *filepath,
320 /* This parameter can only be `const` on Linux since
321 * redirection is not supported there.
322 * NOLINTNEXTLINE: readability-non-const-parameter. */
323 char r_targetpath[FILE_MAXDIR])
324{
325# ifdef WIN32
326 if (!BLI_path_extension_check(filepath, ".lnk")) {
327 return false;
328 }
329
330 HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
331 if (FAILED(hr)) {
332 return false;
333 }
334
335 IShellLinkW *Shortcut = nullptr;
336 hr = CoCreateInstance(
337 CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLinkW, (LPVOID *)&Shortcut);
338
339 bool success = false;
340 if (SUCCEEDED(hr)) {
341 IPersistFile *PersistFile;
342 hr = Shortcut->QueryInterface(IID_IPersistFile, (LPVOID *)&PersistFile);
343 if (SUCCEEDED(hr)) {
344 WCHAR path_utf16[FILE_MAXDIR] = {0};
345 if (conv_utf_8_to_16(filepath, path_utf16, ARRAY_SIZE(path_utf16)) == 0) {
346 hr = PersistFile->Load(path_utf16, STGM_READ);
347 if (SUCCEEDED(hr)) {
348 hr = Shortcut->Resolve(0, SLR_NO_UI | SLR_UPDATE | SLR_NOSEARCH);
349 if (SUCCEEDED(hr)) {
350 wchar_t target_utf16[FILE_MAXDIR] = {0};
351 hr = Shortcut->GetPath(target_utf16, FILE_MAXDIR, nullptr, 0);
352 if (SUCCEEDED(hr)) {
353 success = (conv_utf_16_to_8(target_utf16, r_targetpath, FILE_MAXDIR) == 0);
354 }
355 }
356 PersistFile->Release();
357 }
358 }
359 }
360 Shortcut->Release();
361 }
362
363 CoUninitialize();
364 return (success && r_targetpath[0]);
365# else
366 UNUSED_VARS(r_targetpath, filepath);
367 /* File-based redirection not supported. */
368 return false;
369# endif
370}
371#endif
372
373int BLI_exists(const char *path)
374{
375#if defined(WIN32)
376 BLI_stat_t st;
377 wchar_t *tmp_16 = alloc_utf16_from_8(path, 1);
378 int len, res;
379
380 len = wcslen(tmp_16);
381 /* in Windows #stat doesn't recognize dir ending on a slash
382 * so we remove it here */
383 if ((len > 3) && ELEM(tmp_16[len - 1], L'\\', L'/')) {
384 tmp_16[len - 1] = '\0';
385 }
386 /* two special cases where the trailing slash is needed:
387 * 1. after the share part of a UNC path
388 * 2. after the C:\ when the path is the volume only
389 */
390 if ((len >= 3) && (tmp_16[0] == L'\\') && (tmp_16[1] == L'\\')) {
391 BLI_path_normalize_unc_16(tmp_16);
392 }
393
394 if ((tmp_16[1] == L':') && (tmp_16[2] == L'\0')) {
395 tmp_16[2] = L'\\';
396 tmp_16[3] = L'\0';
397 }
398
399 res = BLI_wstat(tmp_16, &st);
400
401 free(tmp_16);
402 if (res == -1) {
403 return 0;
404 }
405#else
406 struct stat st;
408 if (stat(path, &st)) {
409 return 0;
410 }
411#endif
412 return (st.st_mode);
413}
414
415#ifdef WIN32
416int BLI_fstat(int fd, BLI_stat_t *buffer)
417{
418# if defined(_MSC_VER)
419 return _fstat64(fd, buffer);
420# else
421 return _fstat(fd, buffer);
422# endif
423}
424
425int BLI_stat(const char *path, BLI_stat_t *buffer)
426{
427 int r;
428 UTF16_ENCODE(path);
429
430 r = BLI_wstat(path_16, buffer);
431
432 UTF16_UN_ENCODE(path);
433 return r;
434}
435
436int BLI_wstat(const wchar_t *path, BLI_stat_t *buffer)
437{
438# if defined(_MSC_VER)
439 return _wstat64(path, buffer);
440# else
441 return _wstat(path, buffer);
442# endif
443}
444#else
445int BLI_fstat(int fd, struct stat *buffer)
446{
447 return fstat(fd, buffer);
448}
449
450int BLI_stat(const char *path, struct stat *buffer)
451{
452 return stat(path, buffer);
453}
454#endif
455
456bool BLI_is_dir(const char *path)
457{
458 return S_ISDIR(BLI_exists(path));
459}
460
461bool BLI_is_file(const char *path)
462{
463 const int mode = BLI_exists(path);
464 return (mode && !S_ISDIR(mode));
465}
466
468 bool read_size_exact,
469 size_t pad_bytes,
470 size_t *r_size)
471{
472 /* NOTE: Used for both text and binary file reading. */
473
474 BLI_stat_t st;
475 if (BLI_fstat(fileno(fp), &st) == -1) {
476 return nullptr;
477 }
478 if (S_ISDIR(st.st_mode)) {
479 return nullptr;
480 }
481 if (BLI_fseek(fp, 0L, SEEK_END) == -1) {
482 return nullptr;
483 }
484 /* Don't use the 'st_size' because it may be the symlink. */
485 const long int filelen = BLI_ftell(fp);
486 if (filelen == -1) {
487 return nullptr;
488 }
489 if (BLI_fseek(fp, 0L, SEEK_SET) == -1) {
490 return nullptr;
491 }
492
493 void *mem = MEM_mallocN(filelen + pad_bytes, __func__);
494 if (mem == nullptr) {
495 return nullptr;
496 }
497
498 const long int filelen_read = fread(mem, 1, filelen, fp);
499 if ((filelen_read < 0) || ferror(fp)) {
500 MEM_freeN(mem);
501 return nullptr;
502 }
503
504 if (read_size_exact) {
505 if (filelen_read != filelen) {
506 MEM_freeN(mem);
507 return nullptr;
508 }
509 }
510 else {
511 if (filelen_read < filelen) {
512 mem = MEM_reallocN(mem, filelen_read + pad_bytes);
513 if (mem == nullptr) {
514 return nullptr;
515 }
516 }
517 }
518
519 *r_size = filelen_read;
520
521 return mem;
522}
523
524void *BLI_file_read_text_as_mem(const char *filepath, size_t pad_bytes, size_t *r_size)
525{
526 FILE *fp = BLI_fopen(filepath, "r");
527 void *mem = nullptr;
528 if (fp) {
529 mem = BLI_file_read_data_as_mem_from_handle(fp, false, pad_bytes, r_size);
530 fclose(fp);
531 }
532 return mem;
533}
534
535void *BLI_file_read_binary_as_mem(const char *filepath, size_t pad_bytes, size_t *r_size)
536{
537 FILE *fp = BLI_fopen(filepath, "rb");
538 void *mem = nullptr;
539 if (fp) {
540 mem = BLI_file_read_data_as_mem_from_handle(fp, true, pad_bytes, r_size);
541 fclose(fp);
542 }
543 return mem;
544}
545
547 bool trim_trailing_space,
548 size_t pad_bytes,
549 size_t *r_size)
550{
551 char *mem = static_cast<char *>(BLI_file_read_text_as_mem(filepath, pad_bytes, r_size));
552 if (mem != nullptr) {
553 char *mem_end = mem + *r_size;
554 if (pad_bytes != 0) {
555 *mem_end = '\0';
556 }
557 for (char *p = mem, *p_next; p != mem_end; p = p_next) {
558 p_next = static_cast<char *>(memchr(p, '\n', mem_end - p));
559 if (p_next != nullptr) {
560 if (trim_trailing_space) {
561 for (char *p_trim = p_next - 1; p_trim > p && ELEM(*p_trim, ' ', '\t'); p_trim--) {
562 *p_trim = '\0';
563 }
564 }
565 *p_next = '\0';
566 p_next++;
567 }
568 else {
569 p_next = mem_end;
570 }
571 }
572 }
573 return mem;
574}
575
576LinkNode *BLI_file_read_as_lines(const char *filepath)
577{
578 FILE *fp = BLI_fopen(filepath, "r");
579 LinkNodePair lines = {nullptr, nullptr};
580 char *buf;
581 size_t size;
582
583 if (!fp) {
584 return nullptr;
585 }
586
587 BLI_fseek(fp, 0, SEEK_END);
588 size = size_t(BLI_ftell(fp));
589 BLI_fseek(fp, 0, SEEK_SET);
590
591 if (UNLIKELY(size == size_t(-1))) {
592 fclose(fp);
593 return nullptr;
594 }
595
596 buf = MEM_calloc_arrayN<char>(size, "file_as_lines");
597 if (buf) {
598 size_t i, last = 0;
599
600 /*
601 * size = because on win32 reading
602 * all the bytes in the file will return
603 * less bytes because of `CRNL` changes.
604 */
605 size = fread(buf, 1, size, fp);
606 for (i = 0; i <= size; i++) {
607 if (i == size || buf[i] == '\n') {
608 char *line = BLI_strdupn(&buf[last], i - last);
609 BLI_linklist_append(&lines, line);
610 last = i + 1;
611 }
612 }
613
614 MEM_freeN(buf);
615 }
616
617 fclose(fp);
618
619 return lines.list;
620}
621
623{
624 BLI_linklist_freeN(lines);
625}
626
627bool BLI_file_older(const char *file1, const char *file2)
628{
629 BLI_stat_t st1, st2;
630 if (BLI_stat(file1, &st1)) {
631 return false;
632 }
633 if (BLI_stat(file2, &st2)) {
634 return false;
635 }
636 return (st1.st_mtime < st2.st_mtime);
637}
#define BLI_assert(a)
Definition BLI_assert.h:46
#define BLI_assert_msg(a, msg)
Definition BLI_assert.h:53
File and directory operations.
FILE * BLI_fopen(const char *filepath, const char *mode) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
struct stat BLI_stat_t
eFileAttributes
@ FILE_ATTR_SPARSE_FILE
@ FILE_ATTR_COMPRESSED
@ FILE_ATTR_ENCRYPTED
@ FILE_ATTR_ALIAS
@ FILE_ATTR_TEMPORARY
@ FILE_ATTR_ARCHIVE
@ FILE_ATTR_REPARSE_POINT
@ FILE_ATTR_HIDDEN
@ FILE_ATTR_READONLY
@ FILE_ATTR_SYSTEM
@ FILE_ATTR_OFFLINE
void BLI_kdtree_nd_ free(KDTree *tree)
#define FILE_MAX
void BLI_setenv(const char *env, const char *val) ATTR_NONNULL(1)
const char * BLI_getenv(const char *env) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
bool BLI_path_is_rel(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
bool BLI_path_extension_check(const char *path, const char *ext) ATTR_NONNULL(1
#define FILE_MAXDIR
char * BLI_strdupn(const char *str, size_t len) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition string.cc:30
int char char int int int int size_t BLI_strnlen(const char *str, size_t maxlen) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition string.cc:923
size_t BLI_strncpy_wchar_as_utf8(char *__restrict dst, const wchar_t *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
int BLI_thread_is_main(void)
Definition threads.cc:179
#define ARRAY_SIZE(arr)
#define UNUSED_VARS(...)
#define UNLIKELY(x)
#define ELEM(...)
Compatibility-like things for windows.
#define S_ISDIR(x)
const char * dirname(char *path)
Read Guarded memory(de)allocation.
long long int int64_t
static DBVT_INLINE btScalar size(const btDbvtVolume &a)
Definition btDbvt.cpp:52
#define MEM_reallocN(vmemh, len)
void * MEM_mallocN(size_t len, const char *str)
Definition mallocn.cc:128
void * MEM_calloc_arrayN(size_t len, size_t size, const char *str)
Definition mallocn.cc:123
void MEM_freeN(void *vmemh)
Definition mallocn.cc:113
#define L
return ret
bool BLI_change_working_dir(const char *dir)
Definition storage.cc:63
const char * BLI_dir_home()
Definition storage.cc:110
eFileAttributes BLI_file_attributes(const char *path)
Definition storage.cc:250
int BLI_exists(const char *path)
Definition storage.cc:373
bool BLI_file_older(const char *file1, const char *file2)
Definition storage.cc:627
void BLI_file_free_lines(LinkNode *lines)
Definition storage.cc:622
int BLI_fstat(int fd, struct stat *buffer)
Definition storage.cc:445
LinkNode * BLI_file_read_as_lines(const char *filepath)
Definition storage.cc:576
bool BLI_file_alias_target(const char *filepath, char r_targetpath[FILE_MAXDIR])
Definition storage.cc:319
int BLI_stat(const char *path, struct stat *buffer)
Definition storage.cc:450
size_t BLI_file_descriptor_size(int file)
Definition storage.cc:230
void * BLI_file_read_binary_as_mem(const char *filepath, size_t pad_bytes, size_t *r_size)
Definition storage.cc:535
int64_t BLI_lseek(int fd, int64_t offset, int whence)
Definition storage.cc:221
double BLI_dir_free_space(const char *dir)
Definition storage.cc:134
size_t BLI_file_size(const char *path)
Definition storage.cc:239
bool BLI_is_dir(const char *path)
Definition storage.cc:456
int BLI_fseek(FILE *stream, int64_t offset, int whence)
Definition storage.cc:212
void * BLI_file_read_text_as_mem(const char *filepath, size_t pad_bytes, size_t *r_size)
Definition storage.cc:524
void * BLI_file_read_text_as_mem_with_newline_as_nil(const char *filepath, bool trim_trailing_space, size_t pad_bytes, size_t *r_size)
Definition storage.cc:546
char * BLI_current_working_dir(char *dir, const size_t maxncpy)
Definition storage.cc:85
void * BLI_file_read_data_as_mem_from_handle(FILE *fp, bool read_size_exact, size_t pad_bytes, size_t *r_size)
Definition storage.cc:467
bool BLI_is_file(const char *path)
Definition storage.cc:461
int64_t BLI_ftell(FILE *stream)
Definition storage.cc:203
LinkNode * list
i
Definition text_draw.cc:230
wchar_t * alloc_utf16_from_8(const char *in8, size_t add)
Definition utfconv.cc:292
int conv_utf_8_to_16(const char *in8, wchar_t *out16, size_t size16)
Definition utfconv.cc:182
int conv_utf_16_to_8(const wchar_t *in16, char *out8, size_t size8)
Definition utfconv.cc:116
#define UTF16_ENCODE(in8str)
Definition utfconv.hh:80
#define UTF16_UN_ENCODE(in8str)
Definition utfconv.hh:84
uint len