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"
15 #include "sdk_util/macros.h"
19 GetDentsHelper::GetDentsHelper()
20 : curdir_ino_(0), parentdir_ino_(0), init_defaults_(false) {
24 GetDentsHelper::GetDentsHelper(ino_t curdir_ino
, ino_t parentdir_ino
)
25 : curdir_ino_(curdir_ino
),
26 parentdir_ino_(parentdir_ino
),
27 init_defaults_(true) {
31 void GetDentsHelper::Reset() {
36 void GetDentsHelper::Initialize() {
38 // Add the default entries: "." and ".."
39 AddDirent(curdir_ino_
, ".", 1);
40 AddDirent(parentdir_ino_
, "..", 2);
44 void GetDentsHelper::AddDirent(ino_t ino
, const char* name
, size_t namelen
) {
46 dirents_
.push_back(dirent());
47 dirent
& entry
= dirents_
.back();
49 entry
.d_off
= sizeof(dirent
);
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: %d < %d", size
, sizeof(dirent
));
79 // Force size to a multiple of dirent
80 size
-= size
% sizeof(dirent
);
82 size_t max
= dirents_
.size() * sizeof(dirent
);
84 // OK, trying to read past the end.
88 if (offs
+ size
>= max
)
91 memcpy(pdir
, reinterpret_cast<const char*>(dirents_
.data()) + offs
, size
);
96 } // namespace nacl_io