Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 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. | |
| 4 | |
| 5 // Some common file utilities for plugin code. | |
| 6 | |
| 7 #include "native_client/src/trusted/plugin/file_utils.h" | |
| 8 | |
| 9 #include <fcntl.h> | |
| 10 #include <stdio.h> | |
| 11 #include <stdlib.h> | |
| 12 | |
| 13 #include <sys/stat.h> | |
| 14 #include <sys/types.h> | |
| 15 | |
| 16 #include "native_client/src/include/nacl_scoped_ptr.h" | |
| 17 #include "native_client/src/include/portability_io.h" | |
| 18 #include "native_client/src/include/portability_string.h" | |
| 19 | |
| 20 | |
| 21 namespace plugin { namespace file_utils { | |
|
jvoung (off chromium)
2013/05/23 20:33:19
same, separate lines
eliben
2013/05/23 20:54:25
Done.
| |
| 22 | |
| 23 StatusCode SlurpFile(int32_t fd, | |
| 24 nacl::string& out_buf, | |
| 25 size_t max_size_to_read) { | |
| 26 struct stat stat_buf; | |
| 27 if (fstat(fd, &stat_buf) != 0) { | |
| 28 CLOSE(fd); | |
| 29 return ERROR_STAT; | |
| 30 } | |
| 31 | |
| 32 // Figure out how large a buffer we need to slurp the whole file (with a | |
| 33 // '\0' at the end). | |
| 34 size_t bytes_to_read = static_cast<size_t>(stat_buf.st_size); | |
| 35 if (bytes_to_read > max_size_to_read - 1) { | |
| 36 CLOSE(fd); | |
| 37 return ERROR_FILE_TOO_LARGE; | |
| 38 } | |
| 39 | |
| 40 FILE* input_file = fdopen(fd, "rb"); | |
| 41 if (!input_file) { | |
| 42 CLOSE(fd); | |
| 43 return ERROR_OPEN; | |
| 44 } | |
| 45 // From here on, closing input_file will automatically close fd. | |
| 46 | |
| 47 nacl::scoped_array<char> buffer(new char[bytes_to_read + 1]); | |
| 48 if (buffer == NULL) { | |
| 49 fclose(input_file); | |
| 50 return ERROR_MEM_ALLOC; | |
| 51 } | |
| 52 | |
| 53 size_t total_bytes_read = 0; | |
| 54 while (bytes_to_read > 0) { | |
| 55 size_t bytes_this_read = fread(&buffer[total_bytes_read], | |
| 56 sizeof(char), | |
| 57 bytes_to_read, | |
| 58 input_file); | |
| 59 if (bytes_this_read < bytes_to_read && (feof(input_file) || | |
| 60 ferror(input_file))) { | |
| 61 fclose(input_file); | |
| 62 return ERROR_READ; | |
| 63 } | |
| 64 total_bytes_read += bytes_this_read; | |
| 65 bytes_to_read -= bytes_this_read; | |
| 66 } | |
| 67 | |
| 68 fclose(input_file); | |
| 69 buffer[total_bytes_read] = '\0'; | |
| 70 out_buf = buffer.get(); | |
| 71 return SUCCESS; | |
| 72 } | |
| 73 | |
| 74 } // namespace file_utils | |
| 75 } // namespace plugin | |
| 76 | |
| OLD | NEW |