(root)/
strace-6.5/
tests/
sprintrc.c
       1  /*
       2   * Copyright (c) 2016 Eugene Syromyatnikov <evgsyr@gmail.com>
       3   * Copyright (c) 2016-2021 The strace developers.
       4   * All rights reserved.
       5   *
       6   * SPDX-License-Identifier: GPL-2.0-or-later
       7   */
       8  
       9  #include "tests.h"
      10  #include <stdio.h>
      11  
      12  enum sprintrc_fmt {
      13  	SPRINTRC_FMT_RAW,
      14  	SPRINTRC_FMT_GREP,
      15  };
      16  
      17  /**
      18   * Provides pointer to static string buffer with printed return code in format
      19   * used by strace - with errno and error message.
      20   *
      21   * @param rc  Return code.
      22   * @param fmt Output format. Currently, raw (used for diff matching) and grep
      23   *            (for extended POSIX regex-based pattern matching) formats are
      24   *            supported.
      25   * @return    Pointer to (statically allocated) buffer containing decimal
      26   *            representation of return code and errno/error message in case @rc
      27   *            is equal to -1.
      28   */
      29  static const char *
      30  sprintrc_ex(long rc, enum sprintrc_fmt fmt)
      31  {
      32  	static const char *formats[] = {
      33  		[SPRINTRC_FMT_RAW] = "-1 %s (%m)",
      34  		[SPRINTRC_FMT_GREP] = "-1 %s \\(%m\\)",
      35  	};
      36  	static char buf[4096];
      37  
      38  	if (rc == 0)
      39  		return "0";
      40  
      41  	int ret = (rc == -1)
      42  		? snprintf(buf, sizeof(buf), formats[fmt], errno2name())
      43  		: snprintf(buf, sizeof(buf), "%ld", rc);
      44  
      45  	if (ret < 0)
      46  		perror_msg_and_fail("snprintf");
      47  	if ((size_t) ret >= sizeof(buf))
      48  		error_msg_and_fail("snprintf overflow: got %d, expected"
      49  				   " no more than %zu", ret, sizeof(buf));
      50  
      51  	return buf;
      52  }
      53  
      54  const char *
      55  sprintrc(long rc)
      56  {
      57  	return sprintrc_ex(rc, SPRINTRC_FMT_RAW);
      58  }
      59  
      60  const char *
      61  sprintrc_grep(long rc)
      62  {
      63  	return sprintrc_ex(rc, SPRINTRC_FMT_GREP);
      64  }