| 326 | } |
| 327 | |
| 328 | Status PosixFileSystem::CopyFile(const string& src, const string& target) { |
| 329 | string translated_src = TranslateName(src); |
| 330 | struct stat sbuf; |
| 331 | if (stat(translated_src.c_str(), &sbuf) != 0) { |
| 332 | return IOError(src, errno); |
| 333 | } |
| 334 | int src_fd = open(translated_src.c_str(), O_RDONLY); |
| 335 | if (src_fd < 0) { |
| 336 | return IOError(src, errno); |
| 337 | } |
| 338 | string translated_target = TranslateName(target); |
| 339 | // O_WRONLY | O_CREAT | O_TRUNC: |
| 340 | // Open file for write and if file does not exist, create the file. |
| 341 | // If file exists, truncate its size to 0. |
| 342 | // When creating file, use the same permissions as original |
| 343 | mode_t mode = sbuf.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO); |
| 344 | int target_fd = |
| 345 | open(translated_target.c_str(), O_WRONLY | O_CREAT | O_TRUNC, mode); |
| 346 | if (target_fd < 0) { |
| 347 | close(src_fd); |
| 348 | return IOError(target, errno); |
| 349 | } |
| 350 | int rc = 0; |
| 351 | off_t offset = 0; |
| 352 | std::unique_ptr<char[]> buffer(new char[kPosixCopyFileBufferSize]); |
| 353 | while (offset < sbuf.st_size) { |
| 354 | // Use uint64 for safe compare SSIZE_MAX |
| 355 | uint64 chunk = sbuf.st_size - offset; |
| 356 | if (chunk > SSIZE_MAX) { |
| 357 | chunk = SSIZE_MAX; |
| 358 | } |
| 359 | #if defined(__linux__) && !defined(__ANDROID__) |
| 360 | rc = sendfile(target_fd, src_fd, &offset, static_cast<size_t>(chunk)); |
| 361 | #else |
| 362 | if (chunk > kPosixCopyFileBufferSize) { |
| 363 | chunk = kPosixCopyFileBufferSize; |
| 364 | } |
| 365 | rc = read(src_fd, buffer.get(), static_cast<size_t>(chunk)); |
| 366 | if (rc <= 0) { |
| 367 | break; |
| 368 | } |
| 369 | rc = write(target_fd, buffer.get(), static_cast<size_t>(chunk)); |
| 370 | offset += chunk; |
| 371 | #endif |
| 372 | if (rc <= 0) { |
| 373 | break; |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | Status result = Status::OK(); |
| 378 | if (rc < 0) { |
| 379 | result = IOError(target, errno); |
| 380 | } |
| 381 | |
| 382 | // Keep the error code |
| 383 | rc = close(target_fd); |
| 384 | if (rc < 0 && result == Status::OK()) { |
| 385 | result = IOError(target, errno); |