// Copyright 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/posix/safe_strerror.h"

#include <errno.h>
#include <stdio.h>
#include <string.h>

#include "base/stl_util.h"

namespace base {

void safe_strerror_r(int err, char* buf, size_t len) {
#if defined(__GLIBC__)
  char* ret = strerror_r(err, buf, len);
  if (ret != buf) {
    snprintf(buf, len, "%s", ret);
  }
#else
  int result = strerror_r(err, buf, len);
  if (result != 0) {
    snprintf(buf,
             len,
             "Error %d while retrieving error %d",
             result > 0 ? result : errno,
             err);
  }
#endif
}

std::string safe_strerror(int err) {
  char buf[256];
  safe_strerror_r(err, buf, size(buf));
  return std::string(buf);
}

}  // namespace base

// Copyright 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/posix/safe_strerror.h"

#include <errno.h>
#include <stdio.h>
#include <string.h>

#include "base/stl_util.h"
#include "build/build_config.h"

#if defined(OS_ANDROID)
#include <android/api-level.h>
#endif

namespace base {

void safe_strerror_r(int err, char* buf, size_t len) {
#if defined(__GLIBC__) || \
   (defined(OS_ANDROID) && defined(_GNU_SOURCE) && __ANDROID_API__ >= 23)
  char* ret = strerror_r(err, buf, len);
  if (ret != buf) {
    snprintf(buf, len, "%s", ret);
  }
#else
  int result = strerror_r(err, buf, len);
  if (result != 0) {
    snprintf(buf,
             len,
             "Error %d while retrieving error %d",
             result > 0 ? result : errno,
             err);
  }
#endif
}

std::string safe_strerror(int err) {
  char buf[256];
  safe_strerror_r(err, buf, size(buf));
  return std::string(buf);
}

}  // namespace base

Switch to GNU-style strerror_r when needed on Android.
Switch to GNU-style strerror_r when needed on Android.

Certain Android configurations use GNU-style strerror_r, signaled by
_GNU_SOURCE with __ANDROID_API__ >= 23.

Change-Id: Ie2e8b0c6d7f8a3d18ede379745dff0dbef61970c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/mini_chromium/+/1611030
Reviewed-by: Eric Astor <992ec5ec5e82ac48af0d69cb9a54373e181066b5@google.com>
