xref: /llvm-project/libc/src/stdio/linux/remove.cpp (revision abc49cc19463970d5523d7d3332e4c1f83bc2ef7)
1d23d858dSSiva Chandra Reddy //===-- Linux implementation of remove ------------------------------------===//
2d23d858dSSiva Chandra Reddy //
3d23d858dSSiva Chandra Reddy // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4d23d858dSSiva Chandra Reddy // See https://llvm.org/LICENSE.txt for license information.
5d23d858dSSiva Chandra Reddy // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d23d858dSSiva Chandra Reddy //
7d23d858dSSiva Chandra Reddy //===----------------------------------------------------------------------===//
8d23d858dSSiva Chandra Reddy 
9d23d858dSSiva Chandra Reddy #include "src/stdio/remove.h"
10d23d858dSSiva Chandra Reddy 
11d23d858dSSiva Chandra Reddy #include "src/__support/OSUtil/syscall.h" // For internal syscall function.
12d23d858dSSiva Chandra Reddy #include "src/__support/common.h"
13d23d858dSSiva Chandra Reddy 
14*abc49cc1SJob Henandez Lara #include "hdr/fcntl_macros.h" // For AT_* macros.
155ff3ff33SPetr Hosek #include "src/__support/macros/config.h"
1604a9c625SMichael Jones #include "src/errno/libc_errno.h"
17d23d858dSSiva Chandra Reddy #include <sys/syscall.h> // For syscall numbers.
18d23d858dSSiva Chandra Reddy 
195ff3ff33SPetr Hosek namespace LIBC_NAMESPACE_DECL {
20d23d858dSSiva Chandra Reddy 
21d23d858dSSiva Chandra Reddy LLVM_LIBC_FUNCTION(int, remove, (const char *path)) {
22d23d858dSSiva Chandra Reddy   // We first try unlinking it as a file. If it is ia file, it will succeed. If
23d23d858dSSiva Chandra Reddy   // it fails with EISDIR, we will try unlinking it as a directory.
24b6bc9d72SGuillaume Chatelet   int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_unlinkat, AT_FDCWD, path, 0);
25d23d858dSSiva Chandra Reddy   if (ret == -EISDIR)
26b6bc9d72SGuillaume Chatelet     ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_unlinkat, AT_FDCWD, path,
27f0a3954eSMichael Jones                                             AT_REMOVEDIR);
28d23d858dSSiva Chandra Reddy   if (ret >= 0)
29d23d858dSSiva Chandra Reddy     return 0;
3004a9c625SMichael Jones   libc_errno = -ret;
31d23d858dSSiva Chandra Reddy   return -1;
32d23d858dSSiva Chandra Reddy }
33d23d858dSSiva Chandra Reddy 
345ff3ff33SPetr Hosek } // namespace LIBC_NAMESPACE_DECL
35