File: overflow.writefail.pass.cpp

package info (click to toggle)
llvm-toolchain-21 1%3A21.1.7-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 2,245,064 kB
  • sloc: cpp: 7,619,731; ansic: 1,434,018; asm: 1,058,748; python: 252,740; f90: 94,671; objc: 70,685; lisp: 42,813; pascal: 18,401; sh: 8,601; ml: 5,111; perl: 4,720; makefile: 3,676; awk: 3,523; javascript: 2,409; xml: 892; fortran: 770
file content (72 lines) | stat: -rw-r--r-- 2,070 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: no-filesystem

// setrlimit(RLIMIT_FSIZE) seems to only work as intended on Apple platforms
// REQUIRES: target={{.+}}-apple-{{.+}}

// <fstream>

// Make sure that we properly handle the case where we try to write content to a file
// but we fail to do so because std::fwrite fails.

#include <cassert>
#include <csignal>
#include <cstddef>
#include <fstream>
#include <string>

#include "platform_support.h"
#include "test_macros.h"

#if __has_include(<sys/resource.h>)
#  include <sys/resource.h>
void limit_file_size_to(std::size_t bytes) {
  rlimit lim = {bytes, bytes};
  assert(setrlimit(RLIMIT_FSIZE, &lim) == 0);

  std::signal(SIGXFSZ, [](int) {}); // ignore SIGXFSZ to ensure std::fwrite fails
}
#else
#  error No known way to limit the amount of filesystem space available
#endif

template <class CharT>
void test() {
  std::string temp = get_temp_file_name();
  std::basic_filebuf<CharT> fbuf;
  assert(fbuf.open(temp, std::ios::out | std::ios::trunc));

  std::size_t const limit = 100000;
  limit_file_size_to(limit);

  std::basic_string<CharT> large_block(limit / 10, CharT(42));

  std::streamsize ret;
  std::size_t bytes_written = 0;
  while ((ret = fbuf.sputn(large_block.data(), large_block.size())) != 0) {
    bytes_written += ret;

    // In theory, it's possible for an implementation to allow writing arbitrarily more bytes than
    // set by setrlimit, but in practice if we bust 100x our limit, something else is wrong with the
    // test and we'd end up looping forever.
    assert(bytes_written < 100 * limit);
  }

  fbuf.close();
}

int main(int, char**) {
  test<char>();
#ifndef TEST_HAS_NO_WIDE_CHARACTERS
  test<wchar_t>();
#endif

  return 0;
}