1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/test/test_file_util.h"
10 #include <sys/types.h>
14 #include "base/file_util.h"
15 #include "base/files/file_path.h"
16 #include "base/logging.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/utf_string_conversions.h"
20 using base::MakeAbsoluteFilePath
;
26 // Deny |permission| on the file |path|.
27 bool DenyFilePermission(const base::FilePath
& path
, mode_t permission
) {
29 if (stat(path
.value().c_str(), &stat_buf
) != 0)
31 stat_buf
.st_mode
&= ~permission
;
33 int rv
= HANDLE_EINTR(chmod(path
.value().c_str(), stat_buf
.st_mode
));
37 // Gets a blob indicating the permission information for |path|.
38 // |length| is the length of the blob. Zero on failure.
39 // Returns the blob pointer, or NULL on failure.
40 void* GetPermissionInfo(const base::FilePath
& path
, size_t* length
) {
45 if (stat(path
.value().c_str(), &stat_buf
) != 0)
48 *length
= sizeof(mode_t
);
49 mode_t
* mode
= new mode_t
;
50 *mode
= stat_buf
.st_mode
& ~S_IFMT
; // Filter out file/path kind.
55 // Restores the permission information for |path|, given the blob retrieved
56 // using |GetPermissionInfo()|.
57 // |info| is the pointer to the blob.
58 // |length| is the length of the blob.
59 // Either |info| or |length| may be NULL/0, in which case nothing happens.
60 bool RestorePermissionInfo(const base::FilePath
& path
,
61 void* info
, size_t length
) {
62 if (!info
|| (length
== 0))
65 DCHECK_EQ(sizeof(mode_t
), length
);
66 mode_t
* mode
= reinterpret_cast<mode_t
*>(info
);
68 int rv
= HANDLE_EINTR(chmod(path
.value().c_str(), *mode
));
77 bool DieFileDie(const base::FilePath
& file
, bool recurse
) {
78 // There is no need to workaround Windows problems on POSIX.
80 return base::DeleteFile(file
, recurse
);
83 #if !defined(OS_LINUX) && !defined(OS_MACOSX)
84 bool EvictFileFromSystemCache(const base::FilePath
& file
) {
85 // There doesn't seem to be a POSIX way to cool the disk cache.
91 std::wstring
FilePathAsWString(const base::FilePath
& path
) {
92 return base::UTF8ToWide(path
.value());
94 base::FilePath
WStringAsFilePath(const std::wstring
& path
) {
95 return base::FilePath(base::WideToUTF8(path
));
98 bool MakeFileUnreadable(const base::FilePath
& path
) {
99 return DenyFilePermission(path
, S_IRUSR
| S_IRGRP
| S_IROTH
);
102 bool MakeFileUnwritable(const base::FilePath
& path
) {
103 return DenyFilePermission(path
, S_IWUSR
| S_IWGRP
| S_IWOTH
);
106 PermissionRestorer::PermissionRestorer(const base::FilePath
& path
)
107 : path_(path
), info_(NULL
), length_(0) {
108 info_
= GetPermissionInfo(path_
, &length_
);
109 DCHECK(info_
!= NULL
);
110 DCHECK_NE(0u, length_
);
113 PermissionRestorer::~PermissionRestorer() {
114 if (!RestorePermissionInfo(path_
, info_
, length_
))
118 } // namespace file_util