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 "sdk_util/macros.h"
17 GetDentsHelper::GetDentsHelper(ino_t curdir_ino, ino_t parentdir_ino)
18 : curdir_ino_(curdir_ino), parentdir_ino_(parentdir_ino) {
22 void GetDentsHelper::Reset() {
27 void GetDentsHelper::Initialize() {
28 // Add the default entries: "." and ".."
29 AddDirent(curdir_ino_, ".", 1);
30 AddDirent(parentdir_ino_, "..", 2);
33 void GetDentsHelper::AddDirent(ino_t ino, const char* name, size_t namelen) {
35 dirents_.push_back(dirent());
36 dirent& entry = dirents_.back();
38 entry.d_off = sizeof(dirent);
39 entry.d_reclen = sizeof(dirent);
42 namelen = strlen(name);
44 size_t d_name_max = MEMBER_SIZE(dirent, d_name) - 1; // -1 for \0.
45 size_t copylen = std::min(d_name_max, namelen);
46 strncpy(&entry.d_name[0], name, copylen);
47 entry.d_name[copylen] = 0;
50 Error GetDentsHelper::GetDents(size_t offs,
53 int* out_bytes) const {
56 // If the buffer pointer is invalid, fail
60 // If the buffer is too small, fail
61 if (size < sizeof(dirent))
64 // Force size to a multiple of dirent
65 size -= size % sizeof(dirent);
67 size_t max = dirents_.size() * sizeof(dirent);
69 // OK, trying to read past the end.
73 if (offs + size >= max)
76 memcpy(pdir, reinterpret_cast<const char*>(dirents_.data()) + offs, size);
81 } // namespace nacl_io