1 // Copyright (c) 2013 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 "nacl_io/getdents_helper.h"
13 #include "nacl_io/log.h"
14 #include "nacl_io/osinttypes.h"
16 #include "sdk_util/macros.h"
20 GetDentsHelper::GetDentsHelper()
21 : curdir_ino_(0), parentdir_ino_(0), init_defaults_(false) {
25 GetDentsHelper::GetDentsHelper(ino_t curdir_ino
, ino_t parentdir_ino
)
26 : curdir_ino_(curdir_ino
),
27 parentdir_ino_(parentdir_ino
),
28 init_defaults_(true) {
32 void GetDentsHelper::Reset() {
37 void GetDentsHelper::Initialize() {
39 // Add the default entries: "." and ".."
40 AddDirent(curdir_ino_
, ".", 1);
41 AddDirent(parentdir_ino_
, "..", 2);
45 void GetDentsHelper::AddDirent(ino_t ino
, const char* name
, size_t namelen
) {
47 dirents_
.push_back(dirent());
48 dirent
& entry
= dirents_
.back();
50 entry
.d_reclen
= sizeof(dirent
);
53 namelen
= strlen(name
);
55 size_t d_name_max
= MEMBER_SIZE(dirent
, d_name
) - 1; // -1 for \0.
56 size_t copylen
= std::min(d_name_max
, namelen
);
57 strncpy(&entry
.d_name
[0], name
, copylen
);
58 entry
.d_name
[copylen
] = 0;
61 Error
GetDentsHelper::GetDents(size_t offs
,
64 int* out_bytes
) const {
67 // If the buffer pointer is invalid, fail
69 LOG_TRACE("dirent pointer is NULL.");
73 // If the buffer is too small, fail
74 if (size
< sizeof(dirent
)) {
75 LOG_TRACE("dirent buffer size is too small: %" PRIuS
" < %" PRIuS
"",
76 size
, sizeof(dirent
));
80 // Force size to a multiple of dirent
81 size
-= size
% sizeof(dirent
);
83 size_t max
= dirents_
.size() * sizeof(dirent
);
85 // OK, trying to read past the end.
89 if (offs
+ size
>= max
)
92 memcpy(pdir
, reinterpret_cast<const char*>(dirents_
.data()) + offs
, size
);
97 } // namespace nacl_io