Merge pull request #23157 from markdroth/gpr_asprintf

Replace most uses of gpr_asprintf() with absl calls.
pull/23419/head
Mark D. Roth 4 years ago committed by GitHub
commit 3201d7f7bf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 11
      src/core/ext/filters/client_channel/http_connect_handshaker.cc
  2. 10
      src/core/ext/filters/client_channel/http_proxy.cc
  3. 12
      src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc
  4. 10
      src/core/ext/filters/client_channel/lb_policy/subchannel_list.h
  5. 9
      src/core/ext/filters/client_channel/lb_policy_registry.cc
  6. 11
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc
  7. 14
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc
  8. 13
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc
  9. 14
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc
  10. 79
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc
  11. 27
      src/core/ext/filters/client_channel/resolver_registry.cc
  12. 13
      src/core/ext/filters/client_channel/resolver_result_parsing.cc
  13. 2
      src/core/ext/filters/client_channel/subchannel.cc
  14. 35
      src/core/ext/filters/client_channel/xds/xds_bootstrap.cc
  15. 20
      src/core/ext/filters/client_channel/xds/xds_client.cc
  16. 19
      src/core/ext/filters/client_channel/xds/xds_client_stats.h
  17. 10
      src/core/ext/filters/http/client/http_client_filter.cc
  18. 15
      src/core/ext/filters/http/message_compress/message_decompress_filter.cc
  19. 50
      src/core/ext/filters/load_reporting/server_load_reporting_filter.cc
  20. 7
      src/core/ext/filters/load_reporting/server_load_reporting_filter.h
  21. 30
      src/core/ext/filters/message_size/message_size_filter.cc
  22. 6
      src/core/ext/transport/chttp2/server/chttp2_server.cc
  23. 12
      src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc
  24. 13
      src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc
  25. 49
      src/core/ext/transport/chttp2/transport/flow_control.cc
  26. 21
      src/core/ext/transport/chttp2/transport/frame_data.cc
  27. 10
      src/core/ext/transport/chttp2/transport/frame_goaway.cc
  28. 11
      src/core/ext/transport/chttp2/transport/frame_ping.cc
  29. 25
      src/core/ext/transport/chttp2/transport/frame_rst_stream.cc
  30. 13
      src/core/ext/transport/chttp2/transport/frame_settings.cc
  31. 21
      src/core/ext/transport/chttp2/transport/frame_window_update.cc
  32. 54
      src/core/ext/transport/chttp2/transport/hpack_parser.cc
  33. 30
      src/core/ext/transport/chttp2/transport/hpack_table.cc
  34. 76
      src/core/ext/transport/chttp2/transport/parsing.cc
  35. 20
      src/core/ext/transport/cronet/transport/cronet_transport.cc
  36. 8
      src/core/lib/channel/channel_trace.cc
  37. 20
      src/core/lib/channel/channelz.cc
  38. 14
      src/core/lib/gpr/log_linux.cc
  39. 14
      src/core/lib/gpr/log_posix.cc
  40. 19
      src/core/lib/gpr/string.cc
  41. 6
      src/core/lib/gpr/string.h
  42. 14
      src/core/lib/gprpp/global_config_env.cc
  43. 23
      src/core/lib/http/httpcli.cc
  44. 10
      src/core/lib/http/httpcli_security_connector.cc
  45. 20
      src/core/lib/iomgr/endpoint_pair_posix.cc
  46. 17
      src/core/lib/iomgr/error_cfstream.cc
  47. 11
      src/core/lib/iomgr/ev_epoll1_linux.cc
  48. 30
      src/core/lib/iomgr/ev_epollex_linux.cc
  49. 11
      src/core/lib/iomgr/ev_poll_posix.cc
  50. 31
      src/core/lib/iomgr/resolve_address_custom.cc
  51. 16
      src/core/lib/iomgr/resolve_address_windows.cc
  52. 57
      src/core/lib/iomgr/resource_quota.cc
  53. 12
      src/core/lib/iomgr/sockaddr_utils.cc
  54. 2
      src/core/lib/iomgr/sockaddr_utils.h
  55. 9
      src/core/lib/iomgr/socket_windows.cc
  56. 20
      src/core/lib/iomgr/tcp_client_cfstream.cc
  57. 15
      src/core/lib/iomgr/tcp_client_custom.cc
  58. 63
      src/core/lib/iomgr/tcp_client_posix.cc
  59. 18
      src/core/lib/iomgr/tcp_client_windows.cc
  60. 2
      src/core/lib/iomgr/tcp_custom.cc
  61. 2
      src/core/lib/iomgr/tcp_custom.h
  62. 14
      src/core/lib/iomgr/tcp_server_custom.cc
  63. 44
      src/core/lib/iomgr/tcp_server_posix.cc
  64. 12
      src/core/lib/iomgr/tcp_server_utils_posix_common.cc
  65. 13
      src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc
  66. 26
      src/core/lib/iomgr/tcp_server_windows.cc
  67. 25
      src/core/lib/iomgr/timer_generic.cc
  68. 9
      src/core/lib/iomgr/udp_server.cc
  69. 23
      src/core/lib/iomgr/unix_sockets_posix.cc
  70. 4
      src/core/lib/iomgr/unix_sockets_posix.h
  71. 7
      src/core/lib/iomgr/unix_sockets_posix_noop.cc
  72. 41
      src/core/lib/json/json_reader.cc
  73. 8
      src/core/lib/security/credentials/credentials.h
  74. 14
      src/core/lib/security/credentials/google_default/credentials_generic.cc
  75. 21
      src/core/lib/security/credentials/google_default/google_default_credentials.cc
  76. 11
      src/core/lib/security/credentials/jwt/jwt_credentials.cc
  77. 47
      src/core/lib/security/credentials/oauth2/oauth2_credentials.cc
  78. 12
      src/core/lib/security/credentials/plugin/plugin_credentials.cc
  79. 20
      src/core/lib/security/security_connector/fake/fake_security_connector.cc
  80. 20
      src/core/lib/security/security_connector/ssl/ssl_security_connector.cc
  81. 16
      src/core/lib/security/security_connector/ssl_utils.cc
  82. 38
      src/core/lib/security/security_connector/tls/tls_security_connector.cc
  83. 19
      src/core/lib/security/transport/client_auth_filter.cc
  84. 25
      src/core/lib/security/util/json_util.cc
  85. 39
      src/core/lib/slice/slice.cc
  86. 1
      src/core/lib/slice/slice_internal.h
  87. 65
      src/core/lib/surface/call.cc
  88. 23
      src/core/lib/uri/uri_parser.cc
  89. 16
      test/core/client_channel/parse_address_with_named_scope_id_test.cc
  90. 13
      test/core/client_channel/resolvers/fake_resolver_test.cc
  91. 5
      test/core/end2end/dualstack_socket_test.cc
  92. 25
      test/core/end2end/fixtures/h2_http_proxy.cc
  93. 31
      test/core/end2end/fixtures/h2_uds.cc
  94. 12
      test/core/end2end/fixtures/http_proxy_fixture.cc
  95. 21
      test/core/end2end/goaway_server_test.cc
  96. 13
      test/core/end2end/tests/compressed_payload.cc
  97. 13
      test/core/end2end/tests/high_initial_seqno.cc
  98. 13
      test/core/end2end/tests/hpack_size.cc
  99. 15
      test/core/end2end/tests/invoke_large_request.cc
  100. 11
      test/core/end2end/tests/no_logging.cc
  101. Some files were not shown because too many files have changed in this diff Show More

@ -22,6 +22,8 @@
#include <string.h>
#include "absl/strings/str_cat.h"
#include <grpc/slice_buffer.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
@ -241,11 +243,10 @@ void HttpConnectHandshaker::OnReadDone(void* arg, grpc_error* error) {
// Make sure we got a 2xx response.
if (handshaker->http_response_.status < 200 ||
handshaker->http_response_.status >= 300) {
char* msg;
gpr_asprintf(&msg, "HTTP proxy returned response code %d",
handshaker->http_response_.status);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("HTTP proxy returned response code ",
handshaker->http_response_.status)
.c_str());
handshaker->HandshakeFailedLocked(error);
goto done;
}

@ -23,6 +23,8 @@
#include <stdbool.h>
#include <string.h>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
@ -176,13 +178,13 @@ class HttpProxyMapper : public ProxyMapperInterface {
/* Use base64 encoding for user credentials as stated in RFC 7617 */
char* encoded_user_cred =
grpc_base64_encode(user_cred, strlen(user_cred), 0, 0);
char* header;
gpr_asprintf(&header, "Proxy-Authorization:Basic %s", encoded_user_cred);
std::string header =
absl::StrCat("Proxy-Authorization:Basic ", encoded_user_cred);
gpr_free(encoded_user_cred);
args_to_add[1] = grpc_channel_arg_string_create(
(char*)GRPC_ARG_HTTP_CONNECT_HEADERS, header);
const_cast<char*>(GRPC_ARG_HTTP_CONNECT_HEADERS),
const_cast<char*>(header.c_str()));
*new_args = grpc_channel_args_copy_and_add(args, args_to_add, 2);
gpr_free(header);
} else {
*new_args = grpc_channel_args_copy_and_add(args, args_to_add, 1);
}

@ -65,6 +65,7 @@
#include <string.h>
#include "absl/container/inlined_vector.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
@ -547,12 +548,10 @@ ServerAddressList GrpcLb::Serverlist::GetServerAddressList(
memcpy(lb_token, server.load_balance_token, lb_token_length);
lb_token[lb_token_length] = '\0';
} else {
char* uri = grpc_sockaddr_to_uri(&addr);
gpr_log(GPR_INFO,
"Missing LB token for backend address '%s'. The empty token will "
"be used instead",
uri);
gpr_free(uri);
grpc_sockaddr_to_uri(&addr).c_str());
lb_token[0] = '\0';
}
// Add address.
@ -1458,11 +1457,10 @@ void GrpcLb::ProcessAddressesAndChannelArgsLocked(
balancer_addresses, response_generator_.get(), &args);
// Create balancer channel if needed.
if (lb_channel_ == nullptr) {
char* uri_str;
gpr_asprintf(&uri_str, "fake:///%s", server_name_);
lb_channel_ = CreateGrpclbBalancerChannel(uri_str, *lb_channel_args);
std::string uri_str = absl::StrCat("fake:///", server_name_);
lb_channel_ =
CreateGrpclbBalancerChannel(uri_str.c_str(), *lb_channel_args);
GPR_ASSERT(lb_channel_ != nullptr);
gpr_free(uri_str);
}
// Propagate updates to the LB channel (pick_first) through the fake
// resolver.

@ -390,23 +390,21 @@ SubchannelList<SubchannelListType, SubchannelDataType>::SubchannelList(
if (subchannel == nullptr) {
// Subchannel could not be created.
if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
char* address_uri = grpc_sockaddr_to_uri(&addresses[i].address());
gpr_log(GPR_INFO,
"[%s %p] could not create subchannel for address uri %s, "
"ignoring",
tracer_->name(), policy_, address_uri);
gpr_free(address_uri);
tracer_->name(), policy_,
grpc_sockaddr_to_uri(&addresses[i].address()).c_str());
}
continue;
}
if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
char* address_uri = grpc_sockaddr_to_uri(&addresses[i].address());
gpr_log(GPR_INFO,
"[%s %p] subchannel list %p index %" PRIuPTR
": Created subchannel %p for address uri %s",
tracer_->name(), policy_, this, subchannels_.size(),
subchannel.get(), address_uri);
gpr_free(address_uri);
subchannel.get(),
grpc_sockaddr_to_uri(&addresses[i].address()).c_str());
}
subchannels_.emplace_back(this, addresses[i], std::move(subchannel));
}

@ -23,6 +23,7 @@
#include <string.h>
#include "absl/container/inlined_vector.h"
#include "absl/strings/str_format.h"
#include "src/core/lib/gpr/string.h"
@ -168,11 +169,9 @@ LoadBalancingPolicyRegistry::ParseLoadBalancingConfig(const Json& json,
LoadBalancingPolicyFactory* factory =
g_state->GetLoadBalancingPolicyFactory(policy->first.c_str());
if (factory == nullptr) {
char* msg;
gpr_asprintf(&msg, "Factory not found for policy \"%s\"",
policy->first.c_str());
*error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
*error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("Factory not found for policy \"%s\"", policy->first)
.c_str());
return nullptr;
}
// Parse load balancing config via factory.

@ -23,6 +23,8 @@
#include <ares.h>
#include <string.h>
#include "absl/strings/str_cat.h"
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h"
#include <grpc/support/alloc.h>
@ -155,11 +157,10 @@ grpc_error* grpc_ares_ev_driver_create_locked(
grpc_ares_test_only_inject_config((*ev_driver)->channel);
GRPC_CARES_TRACE_LOG("request:%p grpc_ares_ev_driver_create_locked", request);
if (status != ARES_SUCCESS) {
char* err_msg;
gpr_asprintf(&err_msg, "Failed to init ares channel. C-ares error: %s",
ares_strerror(status));
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(err_msg);
gpr_free(err_msg);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Failed to init ares channel. C-ares error: ",
ares_strerror(status))
.c_str());
gpr_free(*ev_driver);
return err;
}

@ -20,6 +20,8 @@
#include "src/core/lib/iomgr/port.h"
#if GRPC_ARES == 1 && defined(GRPC_UV)
#include "absl/strings/str_format.h"
#include <ares.h>
#include <uv.h>
@ -43,15 +45,14 @@ class GrpcPolledFdLibuv : public GrpcPolledFd {
public:
GrpcPolledFdLibuv(ares_socket_t as,
std::shared_ptr<WorkSerializer> work_serializer)
: as_(as), work_serializer_(std::move(work_serializer)) {
gpr_asprintf(&name_, "c-ares socket: %" PRIdPTR, (intptr_t)as);
: name_(absl::StrFormat("c-ares socket: %" PRIdPTR, (intptr_t)as)),
as_(as),
work_serializer_(std::move(work_serializer)) {
handle_ = new uv_poll_t();
uv_poll_init_socket(uv_default_loop(), handle_, as);
handle_->data = this;
}
~GrpcPolledFdLibuv() { gpr_free(name_); }
void RegisterForOnReadableLocked(grpc_closure* read_closure) override {
GPR_ASSERT(read_closure_ == nullptr);
GPR_ASSERT((poll_events_ & UV_READABLE) == 0);
@ -98,9 +99,10 @@ class GrpcPolledFdLibuv : public GrpcPolledFd {
ares_socket_t GetWrappedAresSocketLocked() override { return as_; }
const char* GetName() override { return name_; }
const char* GetName() override { return name_.c_str(); }
char* name_;
// TODO(apolcyn): Data members should be private.
std::string name_;
ares_socket_t as_;
uv_poll_t* handle_;
grpc_closure* read_closure_ = nullptr;

@ -24,6 +24,8 @@
#include <string.h>
#include <sys/ioctl.h>
#include "absl/strings/str_cat.h"
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h"
#include <grpc/support/alloc.h>
@ -41,15 +43,13 @@ namespace grpc_core {
class GrpcPolledFdPosix : public GrpcPolledFd {
public:
GrpcPolledFdPosix(ares_socket_t as, grpc_pollset_set* driver_pollset_set)
: as_(as) {
gpr_asprintf(&name_, "c-ares fd: %d", (int)as);
fd_ = grpc_fd_create((int)as, name_, false);
: name_(absl::StrCat("c-ares fd: ", (int)as)), as_(as) {
fd_ = grpc_fd_create((int)as, name_.c_str(), false);
driver_pollset_set_ = driver_pollset_set;
grpc_pollset_set_add_fd(driver_pollset_set_, fd_);
}
~GrpcPolledFdPosix() {
gpr_free(name_);
grpc_pollset_set_del_fd(driver_pollset_set_, fd_);
/* c-ares library will close the fd inside grpc_fd. This fd may be picked up
immediately by another thread, and should not be closed by the following
@ -78,9 +78,10 @@ class GrpcPolledFdPosix : public GrpcPolledFd {
ares_socket_t GetWrappedAresSocketLocked() override { return as_; }
const char* GetName() override { return name_; }
const char* GetName() override { return name_.c_str(); }
char* name_;
private:
std::string name_;
ares_socket_t as_;
grpc_fd* fd_;
grpc_pollset_set* driver_pollset_set_;

@ -20,6 +20,8 @@
#include "src/core/lib/iomgr/port.h"
#if GRPC_ARES == 1 && defined(GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER)
#include "absl/strings/str_format.h"
#include <ares.h>
#include <grpc/support/alloc.h>
@ -100,14 +102,14 @@ class GrpcPolledFdWindows {
GrpcPolledFdWindows(ares_socket_t as,
std::shared_ptr<WorkSerializer> work_serializer,
int address_family, int socket_type)
: work_serializer_(std::move(work_serializer)),
: name_(absl::StrFormat("c-ares socket: %" PRIdPTR, as)),
work_serializer_(std::move(work_serializer)),
read_buf_(grpc_empty_slice()),
write_buf_(grpc_empty_slice()),
tcp_write_state_(WRITE_IDLE),
gotten_into_driver_list_(false),
address_family_(address_family),
socket_type_(socket_type) {
gpr_asprintf(&name_, "c-ares socket: %" PRIdPTR, as);
// Closure Initialization
GRPC_CLOSURE_INIT(&outer_read_closure_,
&GrpcPolledFdWindows::OnIocpReadable, this,
@ -118,7 +120,7 @@ class GrpcPolledFdWindows {
GRPC_CLOSURE_INIT(&on_tcp_connect_locked_,
&GrpcPolledFdWindows::OnTcpConnect, this,
grpc_schedule_on_exec_ctx);
winsocket_ = grpc_winsocket_create(as, name_);
winsocket_ = grpc_winsocket_create(as, name_.c_str());
}
~GrpcPolledFdWindows() {
@ -127,7 +129,6 @@ class GrpcPolledFdWindows {
GPR_ASSERT(read_closure_ == nullptr);
GPR_ASSERT(write_closure_ == nullptr);
grpc_winsocket_destroy(winsocket_);
gpr_free(name_);
}
void ScheduleAndNullReadClosure(grpc_error* error) {
@ -260,7 +261,7 @@ class GrpcPolledFdWindows {
return grpc_winsocket_wrapped_socket(winsocket_);
}
const char* GetName() { return name_; }
const char* GetName() { return name_.c_str(); }
ares_ssize_t RecvFrom(WSAErrorContext* wsa_error_ctx, void* data,
ares_socket_t data_len, int flags,
@ -657,6 +658,7 @@ class GrpcPolledFdWindows {
bool gotten_into_driver_list() const { return gotten_into_driver_list_; }
void set_gotten_into_driver_list() { gotten_into_driver_list_ = true; }
private:
std::shared_ptr<WorkSerializer> work_serializer_;
char recv_from_source_addr_[200];
ares_socklen_t recv_from_source_addr_len_;
@ -670,7 +672,7 @@ class GrpcPolledFdWindows {
grpc_winsocket* winsocket_;
// tcp_write_state_ is only used on TCP GrpcPolledFds
WriteState tcp_write_state_;
char* name_ = nullptr;
std::string name_;
bool gotten_into_driver_list_;
int address_family_;
int socket_type_;

@ -27,6 +27,8 @@
#include <sys/types.h>
#include "absl/container/inlined_vector.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include <ares.h>
#include <grpc/support/alloc.h>
@ -277,15 +279,12 @@ static void on_hostbyname_done_locked(void* arg, int status, int /*timeouts*/,
}
}
} else {
char* error_msg;
gpr_asprintf(&error_msg,
"C-ares status is not ARES_SUCCESS "
"qtype=%s name=%s is_balancer=%d: %s",
hr->qtype, hr->host, hr->is_balancer, ares_strerror(status));
std::string error_msg = absl::StrFormat(
"C-ares status is not ARES_SUCCESS qtype=%s name=%s is_balancer=%d: %s",
hr->qtype, hr->host, hr->is_balancer, ares_strerror(status));
GRPC_CARES_TRACE_LOG("request:%p on_hostbyname_done_locked: %s", r,
error_msg);
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg);
gpr_free(error_msg);
error_msg.c_str());
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg.c_str());
r->error = grpc_error_add_child(error, r->error);
}
destroy_hostbyname_request_locked(hr);
@ -326,15 +325,12 @@ static void on_srv_query_done_locked(void* arg, int status, int /*timeouts*/,
ares_free_data(reply);
}
} else {
char* error_msg;
gpr_asprintf(&error_msg,
"C-ares status is not ARES_SUCCESS "
"qtype=SRV name=%s: %s",
q->name().c_str(), ares_strerror(status));
std::string error_msg = absl::StrFormat(
"C-ares status is not ARES_SUCCESS qtype=SRV name=%s: %s", q->name(),
ares_strerror(status));
GRPC_CARES_TRACE_LOG("request:%p on_srv_query_done_locked: %s", r,
error_msg);
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg);
gpr_free(error_msg);
error_msg.c_str());
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg.c_str());
r->error = grpc_error_add_child(error, r->error);
}
delete q;
@ -344,8 +340,8 @@ static const char g_service_config_attribute_prefix[] = "grpc_config=";
static void on_txt_done_locked(void* arg, int status, int /*timeouts*/,
unsigned char* buf, int len) {
char* error_msg;
GrpcAresQuery* q = static_cast<GrpcAresQuery*>(arg);
std::unique_ptr<GrpcAresQuery> query_deleter(q);
grpc_ares_request* r = q->parent_request();
const size_t prefix_len = sizeof(g_service_config_attribute_prefix) - 1;
struct ares_txt_ext* result = nullptr;
@ -386,18 +382,15 @@ static void on_txt_done_locked(void* arg, int status, int /*timeouts*/,
}
// Clean up.
ares_free_data(reply);
goto done;
return;
fail:
gpr_asprintf(&error_msg,
"C-ares status is not ARES_SUCCESS "
"qtype=TXT name=%s: %s",
q->name().c_str(), ares_strerror(status));
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg);
GRPC_CARES_TRACE_LOG("request:%p on_txt_done_locked %s", r, error_msg);
gpr_free(error_msg);
std::string error_msg =
absl::StrFormat("C-ares status is not ARES_SUCCESS qtype=TXT name=%s: %s",
q->name(), ares_strerror(status));
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg.c_str());
GRPC_CARES_TRACE_LOG("request:%p on_txt_done_locked %s", r,
error_msg.c_str());
r->error = grpc_error_add_child(error, r->error);
done:
delete q;
}
void grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked(
@ -459,11 +452,10 @@ void grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked(
}
int status = ares_set_servers_ports(*channel, &r->dns_server_addr);
if (status != ARES_SUCCESS) {
char* error_msg;
gpr_asprintf(&error_msg, "C-ares status is not ARES_SUCCESS: %s",
ares_strerror(status));
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg);
gpr_free(error_msg);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("C-ares status is not ARES_SUCCESS: ",
ares_strerror(status))
.c_str());
goto error_cleanup;
}
}
@ -482,20 +474,16 @@ void grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked(
hr);
if (r->balancer_addresses_out != nullptr) {
/* Query the SRV record */
char* service_name;
gpr_asprintf(&service_name, "_grpclb._tcp.%s", host.c_str());
std::string service_name = absl::StrCat("_grpclb._tcp.", host);
GrpcAresQuery* srv_query = new GrpcAresQuery(r, service_name);
ares_query(*channel, service_name, ns_c_in, ns_t_srv,
ares_query(*channel, service_name.c_str(), ns_c_in, ns_t_srv,
on_srv_query_done_locked, srv_query);
gpr_free(service_name);
}
if (r->service_config_json_out != nullptr) {
char* config_name;
gpr_asprintf(&config_name, "_grpc_config.%s", host.c_str());
std::string config_name = absl::StrCat("_grpc_config.", host);
GrpcAresQuery* txt_query = new GrpcAresQuery(r, config_name);
ares_search(*channel, config_name, ns_c_in, ns_t_txt, on_txt_done_locked,
txt_query);
gpr_free(config_name);
ares_search(*channel, config_name.c_str(), ns_c_in, ns_t_txt,
on_txt_done_locked, txt_query);
}
grpc_ares_ev_driver_start_locked(r->ev_driver);
grpc_ares_request_unref_locked(r);
@ -709,12 +697,9 @@ void (*grpc_cancel_ares_request_locked)(grpc_ares_request* r) =
grpc_error* grpc_ares_init(void) {
int status = ares_library_init(ARES_LIB_INIT_ALL);
if (status != ARES_SUCCESS) {
char* error_msg;
gpr_asprintf(&error_msg, "ares_library_init failed: %s",
ares_strerror(status));
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg);
gpr_free(error_msg);
return error;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("ares_library_init failed: ", ares_strerror(status))
.c_str());
}
return GRPC_ERROR_NONE;
}

@ -23,6 +23,7 @@
#include <string.h>
#include "absl/container/inlined_vector.h"
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
@ -65,22 +66,22 @@ class RegistryState {
// If \a default_prefix_ needs to be prepended, sets \a canonical_target
// to the canonical target string.
ResolverFactory* FindResolverFactory(const char* target, grpc_uri** uri,
char** canonical_target) const {
std::string* canonical_target) const {
GPR_ASSERT(uri != nullptr);
*uri = grpc_uri_parse(target, 1);
ResolverFactory* factory =
*uri == nullptr ? nullptr : LookupResolverFactory((*uri)->scheme);
if (factory == nullptr) {
grpc_uri_destroy(*uri);
gpr_asprintf(canonical_target, "%s%s", default_prefix_.get(), target);
*uri = grpc_uri_parse(*canonical_target, 1);
*canonical_target = absl::StrCat(default_prefix_.get(), target);
*uri = grpc_uri_parse(canonical_target->c_str(), 1);
factory =
*uri == nullptr ? nullptr : LookupResolverFactory((*uri)->scheme);
if (factory == nullptr) {
grpc_uri_destroy(grpc_uri_parse(target, 0));
grpc_uri_destroy(grpc_uri_parse(*canonical_target, 0));
grpc_uri_destroy(grpc_uri_parse(canonical_target->c_str(), 0));
gpr_log(GPR_ERROR, "don't know how to resolve '%s' or '%s'", target,
*canonical_target);
canonical_target->c_str());
}
}
return factory;
@ -136,12 +137,11 @@ ResolverFactory* ResolverRegistry::LookupResolverFactory(const char* scheme) {
bool ResolverRegistry::IsValidTarget(const char* target) {
grpc_uri* uri = nullptr;
char* canonical_target = nullptr;
std::string canonical_target;
ResolverFactory* factory =
g_state->FindResolverFactory(target, &uri, &canonical_target);
bool result = factory == nullptr ? false : factory->IsValidUri(uri);
grpc_uri_destroy(uri);
gpr_free(canonical_target);
return result;
}
@ -152,7 +152,7 @@ OrphanablePtr<Resolver> ResolverRegistry::CreateResolver(
std::unique_ptr<Resolver::ResultHandler> result_handler) {
GPR_ASSERT(g_state != nullptr);
grpc_uri* uri = nullptr;
char* canonical_target = nullptr;
std::string canonical_target;
ResolverFactory* factory =
g_state->FindResolverFactory(target, &uri, &canonical_target);
ResolverArgs resolver_args;
@ -165,7 +165,6 @@ OrphanablePtr<Resolver> ResolverRegistry::CreateResolver(
factory == nullptr ? nullptr
: factory->CreateResolver(std::move(resolver_args));
grpc_uri_destroy(uri);
gpr_free(canonical_target);
return resolver;
}
@ -173,13 +172,12 @@ grpc_core::UniquePtr<char> ResolverRegistry::GetDefaultAuthority(
const char* target) {
GPR_ASSERT(g_state != nullptr);
grpc_uri* uri = nullptr;
char* canonical_target = nullptr;
std::string canonical_target;
ResolverFactory* factory =
g_state->FindResolverFactory(target, &uri, &canonical_target);
grpc_core::UniquePtr<char> authority =
factory == nullptr ? nullptr : factory->GetDefaultAuthority(uri);
grpc_uri_destroy(uri);
gpr_free(canonical_target);
return authority;
}
@ -187,11 +185,12 @@ grpc_core::UniquePtr<char> ResolverRegistry::AddDefaultPrefixIfNeeded(
const char* target) {
GPR_ASSERT(g_state != nullptr);
grpc_uri* uri = nullptr;
char* canonical_target = nullptr;
std::string canonical_target;
g_state->FindResolverFactory(target, &uri, &canonical_target);
grpc_uri_destroy(uri);
return grpc_core::UniquePtr<char>(
canonical_target == nullptr ? gpr_strdup(target) : canonical_target);
return grpc_core::UniquePtr<char>(canonical_target.empty()
? gpr_strdup(target)
: gpr_strdup(canonical_target.c_str()));
}
} // namespace grpc_core

@ -24,6 +24,7 @@
#include <stdio.h>
#include <string.h>
#include "absl/strings/str_cat.h"
#include "absl/types/optional.h"
#include <grpc/support/alloc.h>
@ -353,13 +354,11 @@ ClientChannelServiceConfigParser::ParseGlobalParams(const Json& json,
error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"field:loadBalancingPolicy error:Unknown lb policy"));
} else if (requires_config) {
char* error_msg;
gpr_asprintf(&error_msg,
"field:loadBalancingPolicy error:%s requires a config. "
"Please use loadBalancingConfig instead.",
lb_policy_name.c_str());
error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg));
gpr_free(error_msg);
error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("field:loadBalancingPolicy error:", lb_policy_name,
" requires a config. Please use loadBalancingConfig "
"instead.")
.c_str()));
}
}
}

@ -872,7 +872,7 @@ grpc_arg Subchannel::CreateSubchannelAddressArg(
const grpc_resolved_address* addr) {
return grpc_channel_arg_string_create(
(char*)GRPC_ARG_SUBCHANNEL_ADDRESS,
addr->len > 0 ? grpc_sockaddr_to_uri(addr) : gpr_strdup(""));
gpr_strdup(addr->len > 0 ? grpc_sockaddr_to_uri(addr).c_str() : ""));
}
const char* Subchannel::GetUriFromSubchannelAddressArg(

@ -23,12 +23,11 @@
#include <errno.h>
#include <stdlib.h>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/env.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/iomgr/load_file.h"
@ -98,11 +97,9 @@ std::unique_ptr<XdsBootstrap> XdsBootstrap::ReadFromFile(XdsClient* client,
Json json = Json::Parse(contents_str_view, error);
grpc_slice_unref_internal(contents);
if (*error != GRPC_ERROR_NONE) {
char* msg;
gpr_asprintf(&msg, "Failed to parse bootstrap file %s", path.get());
grpc_error* error_out =
GRPC_ERROR_CREATE_REFERENCING_FROM_COPIED_STRING(msg, error, 1);
gpr_free(msg);
grpc_error* error_out = GRPC_ERROR_CREATE_REFERENCING_FROM_COPIED_STRING(
absl::StrCat("Failed to parse bootstrap file ", path.get()).c_str(),
error, 1);
GRPC_ERROR_UNREF(*error);
*error = error_out;
return nullptr;
@ -154,10 +151,8 @@ grpc_error* XdsBootstrap::ParseXdsServerList(Json* json) {
for (size_t i = 0; i < json->mutable_array()->size(); ++i) {
Json& child = json->mutable_array()->at(i);
if (child.type() != Json::Type::OBJECT) {
char* msg;
gpr_asprintf(&msg, "array element %" PRIuPTR " is not an object", i);
error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg));
gpr_free(msg);
error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("array element ", i, " is not an object").c_str()));
} else {
grpc_error* parse_error = ParseXdsServer(&child, i);
if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error);
@ -194,10 +189,8 @@ grpc_error* XdsBootstrap::ParseXdsServer(Json* json, size_t idx) {
// Can't use GRPC_ERROR_CREATE_FROM_VECTOR() here, because the error
// string is not static in this case.
if (error_list.empty()) return GRPC_ERROR_NONE;
char* msg;
gpr_asprintf(&msg, "errors parsing index %" PRIuPTR, idx);
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("errors parsing index ", idx).c_str());
for (size_t i = 0; i < error_list.size(); ++i) {
error = grpc_error_add_child(error, error_list[i]);
}
@ -210,10 +203,8 @@ grpc_error* XdsBootstrap::ParseChannelCredsArray(Json* json,
for (size_t i = 0; i < json->mutable_array()->size(); ++i) {
Json& child = json->mutable_array()->at(i);
if (child.type() != Json::Type::OBJECT) {
char* msg;
gpr_asprintf(&msg, "array element %" PRIuPTR " is not an object", i);
error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg));
gpr_free(msg);
error_list.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("array element ", i, " is not an object").c_str()));
} else {
grpc_error* parse_error = ParseChannelCreds(&child, i, server);
if (parse_error != GRPC_ERROR_NONE) error_list.push_back(parse_error);
@ -252,10 +243,8 @@ grpc_error* XdsBootstrap::ParseChannelCreds(Json* json, size_t idx,
// Can't use GRPC_ERROR_CREATE_FROM_VECTOR() here, because the error
// string is not static in this case.
if (error_list.empty()) return GRPC_ERROR_NONE;
char* msg;
gpr_asprintf(&msg, "errors parsing index %" PRIuPTR, idx);
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("errors parsing index ", idx).c_str());
for (size_t i = 0; i < error_list.size(); ++i) {
error = grpc_error_add_child(error, error_list[i]);
}

@ -30,7 +30,6 @@
#include <grpc/byte_buffer_reader.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include "src/core/ext/filters/client_channel/client_channel.h"
@ -180,13 +179,11 @@ class XdsClient::ChannelState::AdsCallState
void OnTimerLocked(grpc_error* error) {
if (error == GRPC_ERROR_NONE && timer_pending_) {
timer_pending_ = false;
char* msg;
gpr_asprintf(
&msg,
"timeout obtaining resource {type=%s name=%s} from xds server",
type_url_.c_str(), name_.c_str());
grpc_error* watcher_error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
grpc_error* watcher_error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat(
"timeout obtaining resource {type=%s name=%s} from xds server",
type_url_, name_)
.c_str());
if (GRPC_TRACE_FLAG_ENABLED(grpc_xds_client_trace)) {
gpr_log(GPR_INFO, "[xds_client %p] %s", ads_calld_->xds_client(),
grpc_error_string(watcher_error));
@ -1092,8 +1089,8 @@ void XdsClient::ChannelState::AdsCallState::AcceptEdsUpdate(
"[xds_client %p] Priority %" PRIuPTR ", locality %" PRIuPTR
" %s has weight %d, contains %" PRIuPTR " server addresses",
xds_client(), priority, locality_count,
locality.name->AsHumanReadableString(), locality.lb_weight,
locality.serverlist.size());
locality.name->AsHumanReadableString().c_str(),
locality.lb_weight, locality.serverlist.size());
for (size_t i = 0; i < locality.serverlist.size(); ++i) {
std::string ipport = grpc_sockaddr_to_string(
&locality.serverlist[i].address(), false);
@ -1101,7 +1098,8 @@ void XdsClient::ChannelState::AdsCallState::AcceptEdsUpdate(
"[xds_client %p] Priority %" PRIuPTR ", locality %" PRIuPTR
" %s, server address %" PRIuPTR ": %s",
xds_client(), priority, locality_count,
locality.name->AsHumanReadableString(), i, ipport.c_str());
locality.name->AsHumanReadableString().c_str(), i,
ipport.c_str());
}
++locality_count;
}

@ -24,10 +24,10 @@
#include <map>
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include <grpc/support/string_util.h>
#include "src/core/lib/gprpp/atomic.h"
#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/gprpp/ref_counted.h"
@ -80,21 +80,20 @@ class XdsLocalityName : public RefCounted<XdsLocalityName> {
const std::string& zone() const { return zone_; }
const std::string& sub_zone() const { return sub_zone_; }
const char* AsHumanReadableString() {
if (human_readable_string_ == nullptr) {
char* tmp;
gpr_asprintf(&tmp, "{region=\"%s\", zone=\"%s\", sub_zone=\"%s\"}",
region_.c_str(), zone_.c_str(), sub_zone_.c_str());
human_readable_string_.reset(tmp);
const std::string& AsHumanReadableString() {
if (human_readable_string_.empty()) {
human_readable_string_ =
absl::StrFormat("{region=\"%s\", zone=\"%s\", sub_zone=\"%s\"}",
region_, zone_, sub_zone_);
}
return human_readable_string_.get();
return human_readable_string_;
}
private:
std::string region_;
std::string zone_;
std::string sub_zone_;
UniquePtr<char> human_readable_string_;
std::string human_readable_string_;
};
// Drop stats for an xds cluster.

@ -23,12 +23,12 @@
#include <string>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/filters/http/client/http_client_filter.h"
#include "src/core/lib/gpr/string.h"
@ -121,8 +121,8 @@ static grpc_error* client_filter_incoming_metadata(grpc_metadata_batch* b) {
} else {
char* val = grpc_dump_slice(GRPC_MDVALUE(b->idx.named.status->md),
GPR_DUMP_ASCII);
char* msg;
gpr_asprintf(&msg, "Received http2 header with status: %s", val);
std::string msg =
absl::StrCat("Received http2 header with status: ", val);
grpc_error* e = grpc_error_set_str(
grpc_error_set_int(
grpc_error_set_str(
@ -131,9 +131,9 @@ static grpc_error* client_filter_incoming_metadata(grpc_metadata_batch* b) {
GRPC_ERROR_STR_VALUE, grpc_slice_from_copied_string(val)),
GRPC_ERROR_INT_GRPC_STATUS,
grpc_http2_status_to_grpc_status(atoi(val))),
GRPC_ERROR_STR_GRPC_MESSAGE, grpc_slice_from_copied_string(msg));
GRPC_ERROR_STR_GRPC_MESSAGE,
grpc_slice_from_cpp_string(std::move(msg)));
gpr_free(val);
gpr_free(msg);
return e;
}
}

@ -23,11 +23,12 @@
#include <assert.h>
#include <string.h>
#include "absl/strings/str_cat.h"
#include <grpc/compression.h>
#include <grpc/slice_buffer.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "absl/strings/str_format.h"
#include "src/core/ext/filters/message_size/message_size_filter.h"
@ -258,14 +259,12 @@ void CallData::FinishRecvMessage() {
grpc_slice_buffer_init(&decompressed_slices);
if (grpc_msg_decompress(algorithm_, &recv_slices_, &decompressed_slices) ==
0) {
char* msg;
gpr_asprintf(
&msg,
"Unexpected error decompressing data for algorithm with enum value %d",
algorithm_);
GPR_DEBUG_ASSERT(error_ == GRPC_ERROR_NONE);
error_ = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
error_ = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Unexpected error decompressing data for algorithm with "
"enum value ",
algorithm_)
.c_str());
grpc_slice_buffer_destroy_internal(&decompressed_slices);
} else {
uint32_t recv_flags =

@ -20,11 +20,14 @@
#include <string.h>
#include <string>
#include "absl/strings/str_format.h"
#include <grpc/grpc_security.h>
#include <grpc/slice.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h"
#include "src/core/ext/filters/client_channel/parse_address.h"
@ -121,8 +124,7 @@ void ServerLoadReportingCallData::StartTransportStreamOpBatch(
grpc_call_next_op(elem, op->op());
}
void ServerLoadReportingCallData::GetCensusSafeClientIpString(
char** client_ip_string, size_t* size) {
std::string ServerLoadReportingCallData::GetCensusSafeClientIpString() {
// Find the client URI string.
const char* client_uri_str =
reinterpret_cast<const char*>(gpr_atm_acq_load(peer_string_));
@ -130,9 +132,7 @@ void ServerLoadReportingCallData::GetCensusSafeClientIpString(
gpr_log(GPR_ERROR,
"Unable to extract client URI string (peer string) from gRPC "
"metadata.");
*client_ip_string = nullptr;
*size = 0;
return;
return "";
}
// Parse the client URI string into grpc_uri.
grpc_uri* client_uri = grpc_uri_parse(client_uri_str, true);
@ -140,9 +140,7 @@ void ServerLoadReportingCallData::GetCensusSafeClientIpString(
gpr_log(GPR_ERROR,
"Unable to parse the client URI string (peer string) to a client "
"URI.");
*client_ip_string = nullptr;
*size = 0;
return;
return "";
}
// Parse the client URI into grpc_resolved_address.
grpc_resolved_address resolved_address;
@ -151,26 +149,23 @@ void ServerLoadReportingCallData::GetCensusSafeClientIpString(
if (!success) {
gpr_log(GPR_ERROR,
"Unable to parse client URI into a grpc_resolved_address.");
*client_ip_string = nullptr;
*size = 0;
return;
return "";
}
// Convert the socket address in the grpc_resolved_address into a hex string
// according to the address family.
grpc_sockaddr* addr = reinterpret_cast<grpc_sockaddr*>(resolved_address.addr);
if (addr->sa_family == GRPC_AF_INET) {
grpc_sockaddr_in* addr4 = reinterpret_cast<grpc_sockaddr_in*>(addr);
gpr_asprintf(client_ip_string, "%08x", grpc_ntohl(addr4->sin_addr.s_addr));
*size = 8;
return absl::StrFormat("%08x", grpc_ntohl(addr4->sin_addr.s_addr));
} else if (addr->sa_family == GRPC_AF_INET6) {
grpc_sockaddr_in6* addr6 = reinterpret_cast<grpc_sockaddr_in6*>(addr);
*client_ip_string = static_cast<char*>(gpr_malloc(32 + 1));
std::string client_ip;
client_ip.reserve(32);
uint32_t* addr6_next_long = reinterpret_cast<uint32_t*>(&addr6->sin6_addr);
for (size_t i = 0; i < 4; ++i) {
snprintf(*client_ip_string + 8 * i, 8 + 1, "%08x",
grpc_ntohl(*addr6_next_long++));
absl::StrAppendFormat(&client_ip, "%08x", grpc_ntohl(*addr6_next_long++));
}
*size = 32;
return client_ip;
} else {
GPR_UNREACHABLE_CODE();
}
@ -178,31 +173,28 @@ void ServerLoadReportingCallData::GetCensusSafeClientIpString(
void ServerLoadReportingCallData::StoreClientIpAndLrToken(const char* lr_token,
size_t lr_token_len) {
char* client_ip;
size_t client_ip_len;
GetCensusSafeClientIpString(&client_ip, &client_ip_len);
std::string client_ip = GetCensusSafeClientIpString();
client_ip_and_lr_token_len_ =
kLengthPrefixSize + client_ip_len + lr_token_len;
kLengthPrefixSize + client_ip.size() + lr_token_len;
client_ip_and_lr_token_ = static_cast<char*>(
gpr_zalloc(client_ip_and_lr_token_len_ * sizeof(char)));
char* cur_pos = client_ip_and_lr_token_;
// Store the IP length prefix.
if (client_ip_len == 0) {
if (client_ip.size() == 0) {
strncpy(cur_pos, kEmptyAddressLengthString, kLengthPrefixSize);
} else if (client_ip_len == 8) {
} else if (client_ip.size() == 8) {
strncpy(cur_pos, kEncodedIpv4AddressLengthString, kLengthPrefixSize);
} else if (client_ip_len == 32) {
} else if (client_ip.size() == 32) {
strncpy(cur_pos, kEncodedIpv6AddressLengthString, kLengthPrefixSize);
} else {
GPR_UNREACHABLE_CODE();
}
cur_pos += kLengthPrefixSize;
// Store the IP.
if (client_ip_len != 0) {
strncpy(cur_pos, client_ip, client_ip_len);
if (!client_ip.empty()) {
strncpy(cur_pos, client_ip.c_str(), client_ip.size());
}
gpr_free(client_ip);
cur_pos += client_ip_len;
cur_pos += client_ip.size();
// Store the LR token.
if (lr_token_len != 0) {
strncpy(cur_pos, lr_token, lr_token_len);

@ -21,6 +21,8 @@
#include <grpc/support/port_platform.h>
#include <string>
#include "src/core/lib/channel/channel_stack.h"
#include "src/cpp/common/channel_filter.h"
@ -54,9 +56,8 @@ class ServerLoadReportingCallData : public CallData {
private:
// From the peer_string_ in calld, extracts the client IP string (owned by
// caller), e.g., "01020a0b". Upon failure, set the output pointer to null and
// size to zero.
void GetCensusSafeClientIpString(char** client_ip_string, size_t* size);
// caller), e.g., "01020a0b". Upon failure, returns empty string.
std::string GetCensusSafeClientIpString();
// Concatenates the client IP address and the load reporting token, then
// stores the result into the call data.

@ -21,10 +21,11 @@
#include <limits.h>
#include <string.h>
#include "absl/strings/str_format.h"
#include <grpc/impl/codegen/grpc_types.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/filters/client_channel/service_config.h"
#include "src/core/ext/filters/client_channel/service_config_call_data.h"
@ -198,17 +199,16 @@ static void recv_message_ready(void* user_data, grpc_error* error) {
if (*calld->recv_message != nullptr && calld->limits.max_recv_size >= 0 &&
(*calld->recv_message)->length() >
static_cast<size_t>(calld->limits.max_recv_size)) {
char* message_string;
gpr_asprintf(&message_string,
"Received message larger than max (%u vs. %d)",
(*calld->recv_message)->length(), calld->limits.max_recv_size);
grpc_error* new_error = grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_COPIED_STRING(message_string),
GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("Received message larger than max (%u vs. %d)",
(*calld->recv_message)->length(),
calld->limits.max_recv_size)
.c_str()),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_RESOURCE_EXHAUSTED);
error = grpc_error_add_child(GRPC_ERROR_REF(error), new_error);
GRPC_ERROR_UNREF(calld->error);
calld->error = GRPC_ERROR_REF(error);
gpr_free(message_string);
} else {
GRPC_ERROR_REF(error);
}
@ -258,17 +258,17 @@ static void message_size_start_transport_stream_op_batch(
if (op->send_message && calld->limits.max_send_size >= 0 &&
op->payload->send_message.send_message->length() >
static_cast<size_t>(calld->limits.max_send_size)) {
char* message_string;
gpr_asprintf(&message_string, "Sent message larger than max (%u vs. %d)",
op->payload->send_message.send_message->length(),
calld->limits.max_send_size);
grpc_transport_stream_op_batch_finish_with_failure(
op,
grpc_error_set_int(GRPC_ERROR_CREATE_FROM_COPIED_STRING(message_string),
GRPC_ERROR_INT_GRPC_STATUS,
GRPC_STATUS_RESOURCE_EXHAUSTED),
grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat(
"Sent message larger than max (%u vs. %d)",
op->payload->send_message.send_message->length(),
calld->limits.max_send_size)
.c_str()),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_RESOURCE_EXHAUSTED),
calld->call_combiner);
gpr_free(message_string);
return;
}
// Inject callback for receiving a message.

@ -24,15 +24,15 @@
#include <limits.h>
#include <string.h>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include <grpc/grpc.h>
#include <grpc/impl/codegen/grpc_types.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/sync.h>
#include "absl/strings/str_format.h"
#include "src/core/ext/filters/http/server/http_server_filter.h"
#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
#include "src/core/ext/transport/chttp2/transport/internal.h"

@ -24,8 +24,9 @@
#ifdef GPR_SUPPORT_CHANNELS_FROM_FD
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
#include "src/core/lib/channel/channel_args.h"
@ -40,14 +41,11 @@ void grpc_server_add_insecure_channel_from_fd(grpc_server* server,
GPR_ASSERT(reserved == nullptr);
grpc_core::ExecCtx exec_ctx;
char* name;
gpr_asprintf(&name, "fd:%d", fd);
std::string name = absl::StrCat("fd:", fd);
grpc_endpoint* server_endpoint =
grpc_tcp_create(grpc_fd_create(fd, name, true),
grpc_server_get_channel_args(server), name);
gpr_free(name);
grpc_tcp_create(grpc_fd_create(fd, name.c_str(), true),
grpc_server_get_channel_args(server), name.c_str());
const grpc_channel_args* server_args = grpc_server_get_channel_args(server);
grpc_transport* transport = grpc_create_chttp2_transport(

@ -22,9 +22,10 @@
#include <string.h>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/transport/chttp2/server/chttp2_server.h"
@ -56,12 +57,10 @@ int grpc_server_add_secure_http2_port(grpc_server* server, const char* addr,
}
sc = creds->create_security_connector();
if (sc == nullptr) {
char* msg;
gpr_asprintf(&msg,
"Unable to create secure server with credentials of type %s.",
creds->type());
err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Unable to create secure server with credentials of type ",
creds->type())
.c_str());
goto done;
}
// Create channel args.

@ -25,9 +25,12 @@
#include <math.h>
#include <string.h>
#include <string>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/transport/chttp2/transport/internal.h"
#include "src/core/lib/gpr/string.h"
@ -43,27 +46,23 @@ static constexpr const int kTracePadding = 30;
static constexpr const uint32_t kMaxWindowUpdateSize = (1u << 31) - 1;
static char* fmt_int64_diff_str(int64_t old_val, int64_t new_val) {
char* str;
std::string str;
if (old_val != new_val) {
gpr_asprintf(&str, "%" PRId64 " -> %" PRId64 "", old_val, new_val);
str = absl::StrFormat("%" PRId64 " -> %" PRId64 "", old_val, new_val);
} else {
gpr_asprintf(&str, "%" PRId64 "", old_val);
str = absl::StrFormat("%" PRId64 "", old_val);
}
char* str_lp = gpr_leftpad(str, ' ', kTracePadding);
gpr_free(str);
return str_lp;
return gpr_leftpad(str.c_str(), ' ', kTracePadding);
}
static char* fmt_uint32_diff_str(uint32_t old_val, uint32_t new_val) {
char* str;
std::string str;
if (old_val != new_val) {
gpr_asprintf(&str, "%" PRIu32 " -> %" PRIu32 "", old_val, new_val);
str = absl::StrFormat("%" PRIu32 " -> %" PRIu32 "", old_val, new_val);
} else {
gpr_asprintf(&str, "%" PRIu32 "", old_val);
str = absl::StrFormat("%" PRIu32 "", old_val);
}
char* str_lp = gpr_leftpad(str, ' ', kTracePadding);
gpr_free(str);
return str_lp;
return gpr_leftpad(str.c_str(), ' ', kTracePadding);
}
} // namespace
@ -204,13 +203,11 @@ uint32_t TransportFlowControl::MaybeSendUpdate(bool writing_anyway) {
grpc_error* TransportFlowControl::ValidateRecvData(
int64_t incoming_frame_size) {
if (incoming_frame_size > announced_window_) {
char* msg;
gpr_asprintf(&msg,
"frame of size %" PRId64 " overflows local window of %" PRId64,
incoming_frame_size, announced_window_);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("frame of size %" PRId64
" overflows local window of %" PRId64,
incoming_frame_size, announced_window_)
.c_str());
}
return GRPC_ERROR_NONE;
}
@ -248,13 +245,11 @@ grpc_error* StreamFlowControl::RecvData(int64_t incoming_frame_size) {
"See (for example) https://github.com/netty/netty/issues/6520.",
incoming_frame_size, acked_stream_window, sent_stream_window);
} else {
char* msg;
gpr_asprintf(
&msg, "frame of size %" PRId64 " overflows local window of %" PRId64,
incoming_frame_size, acked_stream_window);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("frame of size %" PRId64
" overflows local window of %" PRId64,
incoming_frame_size, acked_stream_window)
.c_str());
}
}

@ -22,9 +22,10 @@
#include <string.h>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/transport/chttp2/transport/internal.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/memory.h"
@ -44,13 +45,10 @@ grpc_error* grpc_chttp2_data_parser_begin_frame(
grpc_chttp2_data_parser* /*parser*/, uint8_t flags, uint32_t stream_id,
grpc_chttp2_stream* s) {
if (flags & ~GRPC_CHTTP2_DATA_FLAG_END_STREAM) {
char* msg;
gpr_asprintf(&msg, "unsupported data flags: 0x%02x", flags);
grpc_error* err = grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg), GRPC_ERROR_INT_STREAM_ID,
static_cast<intptr_t>(stream_id));
gpr_free(msg);
return err;
return grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("unsupported data flags: 0x%02x", flags).c_str()),
GRPC_ERROR_INT_STREAM_ID, static_cast<intptr_t>(stream_id));
}
if (flags & GRPC_CHTTP2_DATA_FLAG_END_STREAM) {
@ -130,12 +128,11 @@ grpc_error* grpc_deframe_unprocessed_incoming_frames(
p->is_frame_compressed = true; /* GPR_TRUE */
break;
default:
char* msg;
gpr_asprintf(&msg, "Bad GRPC frame type 0x%02x", p->frame_type);
p->error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
p->error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("Bad GRPC frame type 0x%02x", p->frame_type)
.c_str());
p->error = grpc_error_set_int(p->error, GRPC_ERROR_INT_STREAM_ID,
static_cast<intptr_t>(s->id));
gpr_free(msg);
p->error = grpc_error_set_str(
p->error, GRPC_ERROR_STR_RAW_BYTES,
grpc_slice_from_moved_string(grpc_core::UniquePtr<char>(

@ -23,9 +23,10 @@
#include <string.h>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
void grpc_chttp2_goaway_parser_init(grpc_chttp2_goaway_parser* p) {
p->debug_data = nullptr;
@ -39,11 +40,8 @@ grpc_error* grpc_chttp2_goaway_parser_begin_frame(grpc_chttp2_goaway_parser* p,
uint32_t length,
uint8_t /*flags*/) {
if (length < 8) {
char* msg;
gpr_asprintf(&msg, "goaway frame too short (%d bytes)", length);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("goaway frame too short (%d bytes)", length).c_str());
}
gpr_free(p->debug_data);

@ -23,9 +23,10 @@
#include <string.h>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
static bool g_disable_ping_ack = false;
@ -58,11 +59,9 @@ grpc_error* grpc_chttp2_ping_parser_begin_frame(grpc_chttp2_ping_parser* parser,
uint32_t length,
uint8_t flags) {
if (flags & 0xfe || length != 8) {
char* msg;
gpr_asprintf(&msg, "invalid ping: length=%d, flags=%02x", length, flags);
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return error;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("invalid ping: length=%d, flags=%02x", length, flags)
.c_str());
}
parser->byte = 0;
parser->is_ack = flags;

@ -21,9 +21,11 @@
#include "src/core/ext/transport/chttp2/transport/frame_rst_stream.h"
#include "src/core/ext/transport/chttp2/transport/internal.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/transport/chttp2/transport/frame.h"
#include "src/core/lib/gprpp/memory.h"
@ -69,12 +71,10 @@ void grpc_chttp2_add_rst_stream_to_next_write(
grpc_error* grpc_chttp2_rst_stream_parser_begin_frame(
grpc_chttp2_rst_stream_parser* parser, uint32_t length, uint8_t flags) {
if (length != 4) {
char* msg;
gpr_asprintf(&msg, "invalid rst_stream: length=%d, flags=%02x", length,
flags);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("invalid rst_stream: length=%d, flags=%02x", length,
flags)
.c_str());
}
parser->byte = 0;
return GRPC_ERROR_NONE;
@ -106,13 +106,12 @@ grpc_error* grpc_chttp2_rst_stream_parser_parse(void* parser,
((static_cast<uint32_t>(p->reason_bytes[3])));
grpc_error* error = GRPC_ERROR_NONE;
if (reason != GRPC_HTTP2_NO_ERROR || s->metadata_buffer[1].size == 0) {
char* message;
gpr_asprintf(&message, "Received RST_STREAM with error code %d", reason);
error = grpc_error_set_int(
grpc_error_set_str(GRPC_ERROR_CREATE_FROM_STATIC_STRING("RST_STREAM"),
GRPC_ERROR_STR_GRPC_MESSAGE,
grpc_slice_from_moved_string(
grpc_core::UniquePtr<char>(message))),
grpc_error_set_str(
GRPC_ERROR_CREATE_FROM_STATIC_STRING("RST_STREAM"),
GRPC_ERROR_STR_GRPC_MESSAGE,
grpc_slice_from_cpp_string(absl::StrCat(
"Received RST_STREAM with error code ", reason))),
GRPC_ERROR_INT_HTTP2_ERROR, static_cast<intptr_t>(reason));
}
grpc_chttp2_mark_stream_closed(t, s, true, true, error);

@ -23,9 +23,10 @@
#include <string.h>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
#include "src/core/ext/transport/chttp2/transport/frame.h"
@ -117,7 +118,6 @@ grpc_error* grpc_chttp2_settings_parser_parse(void* p, grpc_chttp2_transport* t,
static_cast<grpc_chttp2_settings_parser*>(p);
const uint8_t* cur = GRPC_SLICE_START_PTR(slice);
const uint8_t* end = GRPC_SLICE_END_PTR(slice);
char* msg;
grpc_chttp2_setting_id id;
if (parser->is_ack) {
@ -208,11 +208,10 @@ grpc_error* grpc_chttp2_settings_parser_parse(void* p, grpc_chttp2_transport* t,
t->last_new_stream_id, sp->error_value,
grpc_slice_from_static_string("HTTP2 settings error"),
&t->qbuf);
gpr_asprintf(&msg, "invalid value %u passed for %s",
parser->value, sp->name);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("invalid value %u passed for %s",
parser->value, sp->name)
.c_str());
}
}
if (id == GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE &&

@ -21,9 +21,11 @@
#include "src/core/ext/transport/chttp2/transport/frame_window_update.h"
#include "src/core/ext/transport/chttp2/transport/internal.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
grpc_slice grpc_chttp2_window_update_create(
uint32_t id, uint32_t window_update, grpc_transport_one_way_stats* stats) {
@ -54,12 +56,10 @@ grpc_slice grpc_chttp2_window_update_create(
grpc_error* grpc_chttp2_window_update_parser_begin_frame(
grpc_chttp2_window_update_parser* parser, uint32_t length, uint8_t flags) {
if (flags || length != 4) {
char* msg;
gpr_asprintf(&msg, "invalid window update: length=%d, flags=%02x", length,
flags);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("invalid window update: length=%d, flags=%02x", length,
flags)
.c_str());
}
parser->byte = 0;
parser->amount = 0;
@ -91,11 +91,8 @@ grpc_error* grpc_chttp2_window_update_parser_parse(void* parser,
// top bit is reserved and must be ignored.
uint32_t received_update = p->amount & 0x7fffffffu;
if (received_update == 0) {
char* msg;
gpr_asprintf(&msg, "invalid window update bytes: %d", p->amount);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("invalid window update bytes: ", p->amount).c_str());
}
GPR_ASSERT(is_last);

@ -25,9 +25,11 @@
#include <stddef.h>
#include <string.h>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/transport/chttp2/transport/bin_encoder.h"
#include "src/core/lib/debug/stats.h"
@ -1087,10 +1089,8 @@ static grpc_error* still_parse_error(grpc_chttp2_hpack_parser* p,
static grpc_error* parse_illegal_op(grpc_chttp2_hpack_parser* p,
const uint8_t* cur, const uint8_t* end) {
GPR_ASSERT(cur != end);
char* msg;
gpr_asprintf(&msg, "Illegal hpack op code %d", *cur);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Illegal hpack op code ", *cur).c_str());
return parse_error(p, cur, end, err);
}
@ -1173,7 +1173,6 @@ static grpc_error* parse_value4(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
uint8_t c;
uint32_t cur_value;
uint32_t add_value;
char* msg;
if (cur == end) {
p->state = parse_value4;
@ -1200,12 +1199,12 @@ static grpc_error* parse_value4(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
}
error:
gpr_asprintf(&msg,
"integer overflow in hpack integer decoding: have 0x%08x, "
"got byte 0x%02x on byte 5",
*p->parsing.value, *cur);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat(
"integer overflow in hpack integer decoding: have 0x%08x, "
"got byte 0x%02x on byte 5",
*p->parsing.value, *cur)
.c_str());
return parse_error(p, cur, end, err);
}
@ -1227,13 +1226,12 @@ static grpc_error* parse_value5up(grpc_chttp2_hpack_parser* p,
return parse_next(p, cur + 1, end);
}
char* msg;
gpr_asprintf(&msg,
"integer overflow in hpack integer decoding: have 0x%08x, "
"got byte 0x%02x sometime after byte 5",
*p->parsing.value, *cur);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat(
"integer overflow in hpack integer decoding: have 0x%08x, "
"got byte 0x%02x sometime after byte 5",
*p->parsing.value, *cur)
.c_str());
return parse_error(p, cur, end, err);
}
@ -1389,11 +1387,10 @@ static grpc_error* finish_str(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
case B64_BYTE2:
bits = p->base64_buffer;
if (bits & 0xffff) {
char* msg;
gpr_asprintf(&msg, "trailing bits in base64 encoding: 0x%04x",
bits & 0xffff);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("trailing bits in base64 encoding: 0x%04x",
bits & 0xffff)
.c_str());
return parse_error(p, cur, end, err);
}
decoded[0] = static_cast<uint8_t>(bits >> 16);
@ -1402,11 +1399,10 @@ static grpc_error* finish_str(grpc_chttp2_hpack_parser* p, const uint8_t* cur,
case B64_BYTE3:
bits = p->base64_buffer;
if (bits & 0xff) {
char* msg;
gpr_asprintf(&msg, "trailing bits in base64 encoding: 0x%02x",
bits & 0xff);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("trailing bits in base64 encoding: 0x%02x",
bits & 0xff)
.c_str());
return parse_error(p, cur, end, err);
}
decoded[0] = static_cast<uint8_t>(bits >> 16);

@ -23,9 +23,10 @@
#include <assert.h>
#include <string.h>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gpr/murmur_hash.h"
@ -119,13 +120,11 @@ grpc_error* grpc_chttp2_hptbl_set_current_table_size(grpc_chttp2_hptbl* tbl,
return GRPC_ERROR_NONE;
}
if (bytes > tbl->max_bytes) {
char* msg;
gpr_asprintf(&msg,
"Attempt to make hpack table %d bytes when max is %d bytes",
bytes, tbl->max_bytes);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat(
"Attempt to make hpack table %d bytes when max is %d bytes", bytes,
tbl->max_bytes)
.c_str());
}
if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) {
gpr_log(GPR_INFO, "Update hpack parser table size to %d", bytes);
@ -153,15 +152,12 @@ grpc_error* grpc_chttp2_hptbl_add(grpc_chttp2_hptbl* tbl, grpc_mdelem md) {
GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD;
if (tbl->current_table_bytes > tbl->max_bytes) {
char* msg;
gpr_asprintf(
&msg,
"HPACK max table size reduced to %d but not reflected by hpack "
"stream (still at %d)",
tbl->max_bytes, tbl->current_table_bytes);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat(
"HPACK max table size reduced to %d but not reflected by hpack "
"stream (still at %d)",
tbl->max_bytes, tbl->current_table_bytes)
.c_str());
}
/* we can't add elements bigger than the max table size */

@ -22,9 +22,11 @@
#include <string.h>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/profiling/timers.h"
#include "src/core/lib/slice/slice_string_helpers.h"
@ -85,18 +87,15 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
case GRPC_DTS_CLIENT_PREFIX_23:
while (cur != end && t->deframe_state != GRPC_DTS_FH_0) {
if (*cur != GRPC_CHTTP2_CLIENT_CONNECT_STRING[t->deframe_state]) {
char* msg;
gpr_asprintf(
&msg,
"Connect string mismatch: expected '%c' (%d) got '%c' (%d) "
"at byte %d",
GRPC_CHTTP2_CLIENT_CONNECT_STRING[t->deframe_state],
static_cast<int>(static_cast<uint8_t>(
GRPC_CHTTP2_CLIENT_CONNECT_STRING[t->deframe_state])),
*cur, static_cast<int>(*cur), t->deframe_state);
err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat(
"Connect string mismatch: expected '%c' (%d) got '%c' (%d) "
"at byte %d",
GRPC_CHTTP2_CLIENT_CONNECT_STRING[t->deframe_state],
static_cast<int>(static_cast<uint8_t>(
GRPC_CHTTP2_CLIENT_CONNECT_STRING[t->deframe_state])),
*cur, static_cast<int>(*cur), t->deframe_state)
.c_str());
}
++cur;
t->deframe_state = static_cast<grpc_chttp2_deframe_transport_state>(
@ -194,14 +193,12 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
t->incoming_frame_size >
t->settings[GRPC_ACKED_SETTINGS]
[GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE]) {
char* msg;
gpr_asprintf(&msg, "Frame size %d is larger than max frame size %d",
t->incoming_frame_size,
t->settings[GRPC_ACKED_SETTINGS]
[GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE]);
err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("Frame size %d is larger than max frame size %d",
t->incoming_frame_size,
t->settings[GRPC_ACKED_SETTINGS]
[GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE])
.c_str());
}
if (++cur == end) {
return GRPC_ERROR_NONE;
@ -255,34 +252,27 @@ grpc_error* grpc_chttp2_perform_read(grpc_chttp2_transport* t,
static grpc_error* init_frame_parser(grpc_chttp2_transport* t) {
if (t->is_first_frame &&
t->incoming_frame_type != GRPC_CHTTP2_FRAME_SETTINGS) {
char* msg;
gpr_asprintf(
&msg, "Expected SETTINGS frame as the first frame, got frame type %d",
t->incoming_frame_type);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat(
"Expected SETTINGS frame as the first frame, got frame type ",
t->incoming_frame_type)
.c_str());
}
t->is_first_frame = false;
if (t->expect_continuation_stream_id != 0) {
if (t->incoming_frame_type != GRPC_CHTTP2_FRAME_CONTINUATION) {
char* msg;
gpr_asprintf(&msg, "Expected CONTINUATION frame, got frame type %02x",
t->incoming_frame_type);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("Expected CONTINUATION frame, got frame type %02x",
t->incoming_frame_type)
.c_str());
}
if (t->expect_continuation_stream_id != t->incoming_stream_id) {
char* msg;
gpr_asprintf(
&msg,
"Expected CONTINUATION frame for grpc_chttp2_stream %08x, got "
"grpc_chttp2_stream %08x",
t->expect_continuation_stream_id, t->incoming_stream_id);
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat(
"Expected CONTINUATION frame for grpc_chttp2_stream %08x, got "
"grpc_chttp2_stream %08x",
t->expect_continuation_stream_id, t->incoming_stream_id)
.c_str());
}
return init_header_frame_parser(t, 1);
}

@ -20,10 +20,13 @@
#include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/slice_buffer.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/transport/chttp2/transport/bin_decoder.h"
#include "src/core/ext/transport/chttp2/transport/bin_encoder.h"
@ -728,7 +731,7 @@ static void create_grpc_frame(grpc_slice_buffer* write_slice_buffer,
Convert metadata in a format that Cronet can consume
*/
static void convert_metadata_to_cronet_headers(
grpc_metadata_batch* metadata, const char* host, char** pp_url,
grpc_metadata_batch* metadata, const char* host, std::string* pp_url,
bidirectional_stream_header** pp_headers, size_t* p_num_headers,
const char** method) {
grpc_linked_mdelem* curr = metadata->list.head;
@ -789,7 +792,7 @@ static void convert_metadata_to_cronet_headers(
}
if (grpc_slice_eq_static_interned(GRPC_MDKEY(mdelem), GRPC_MDSTR_PATH)) {
/* Create URL by appending :path value to the hostname */
gpr_asprintf(pp_url, "https://%s%s", host, value);
*pp_url = absl::StrCat("https://", host, value);
gpr_free(key);
gpr_free(value);
continue;
@ -1051,7 +1054,7 @@ static enum e_op_result execute_stream_op(struct op_and_state* oas) {
bidirectional_stream_disable_auto_flush(s->cbs, true);
bidirectional_stream_delay_request_headers_until_flush(s->cbs, true);
}
char* url = nullptr;
std::string url;
const char* method = "POST";
s->header_array.headers = nullptr;
convert_metadata_to_cronet_headers(
@ -1059,11 +1062,10 @@ static enum e_op_result execute_stream_op(struct op_and_state* oas) {
t->host, &url, &s->header_array.headers, &s->header_array.count,
&method);
s->header_array.capacity = s->header_array.count;
CRONET_LOG(GPR_DEBUG, "bidirectional_stream_start(%p, %s)", s->cbs, url);
bidirectional_stream_start(s->cbs, url, 0, method, &s->header_array, false);
if (url) {
gpr_free(url);
}
CRONET_LOG(GPR_DEBUG, "bidirectional_stream_start(%p, %s)", s->cbs,
url.c_str());
bidirectional_stream_start(s->cbs, url.c_str(), 0, method, &s->header_array,
false);
unsigned int header_index;
for (header_index = 0; header_index < s->header_array.count;
header_index++) {

@ -146,14 +146,12 @@ const char* severity_string(ChannelTrace::Severity severity) {
Json ChannelTrace::TraceEvent::RenderTraceEvent() const {
char* description = grpc_slice_to_c_string(data_);
char* ts_str = gpr_format_timespec(timestamp_);
Json::Object object = {
{"description", description},
{"severity", severity_string(severity_)},
{"timestamp", ts_str},
{"timestamp", gpr_format_timespec(timestamp_)},
};
gpr_free(description);
gpr_free(ts_str);
if (referenced_entity_ != nullptr) {
const bool is_channel =
(referenced_entity_->type() == BaseNode::EntityType::kTopLevelChannel ||
@ -171,11 +169,9 @@ Json ChannelTrace::RenderJson() const {
if (max_event_memory_ == 0) {
return Json(); // JSON null
}
char* ts_str = gpr_format_timespec(time_created_);
Json::Object object = {
{"creationTimestamp", ts_str},
{"creationTimestamp", gpr_format_timespec(time_created_)},
};
gpr_free(ts_str);
if (num_events_logged_ > 0) {
object["numEventsLogged"] = std::to_string(num_events_logged_);
}

@ -156,9 +156,7 @@ void CallCountingHelper::PopulateCallCounts(Json::Object* object) {
gpr_timespec ts = gpr_convert_clock_type(
gpr_cycle_counter_to_time(data.last_call_started_cycle),
GPR_CLOCK_REALTIME);
char* ts_str = gpr_format_timespec(ts);
(*object)["lastCallStartedTimestamp"] = ts_str;
gpr_free(ts_str);
(*object)["lastCallStartedTimestamp"] = gpr_format_timespec(ts);
}
if (data.calls_succeeded != 0) {
(*object)["callsSucceeded"] = std::to_string(data.calls_succeeded);
@ -456,9 +454,7 @@ Json SocketNode::RenderJson() {
ts = gpr_convert_clock_type(
gpr_cycle_counter_to_time(last_local_stream_created_cycle),
GPR_CLOCK_REALTIME);
char* ts_str = gpr_format_timespec(ts);
data["lastLocalStreamCreatedTimestamp"] = ts_str;
gpr_free(ts_str);
data["lastLocalStreamCreatedTimestamp"] = gpr_format_timespec(ts);
}
gpr_cycle_counter last_remote_stream_created_cycle =
last_remote_stream_created_cycle_.Load(MemoryOrder::RELAXED);
@ -466,9 +462,7 @@ Json SocketNode::RenderJson() {
ts = gpr_convert_clock_type(
gpr_cycle_counter_to_time(last_remote_stream_created_cycle),
GPR_CLOCK_REALTIME);
char* ts_str = gpr_format_timespec(ts);
data["lastRemoteStreamCreatedTimestamp"] = ts_str;
gpr_free(ts_str);
data["lastRemoteStreamCreatedTimestamp"] = gpr_format_timespec(ts);
}
}
int64_t streams_succeeded = streams_succeeded_.Load(MemoryOrder::RELAXED);
@ -486,9 +480,7 @@ Json SocketNode::RenderJson() {
gpr_cycle_counter_to_time(
last_message_sent_cycle_.Load(MemoryOrder::RELAXED)),
GPR_CLOCK_REALTIME);
char* ts_str = gpr_format_timespec(ts);
data["lastMessageSentTimestamp"] = ts_str;
gpr_free(ts_str);
data["lastMessageSentTimestamp"] = gpr_format_timespec(ts);
}
int64_t messages_received = messages_received_.Load(MemoryOrder::RELAXED);
if (messages_received != 0) {
@ -497,9 +489,7 @@ Json SocketNode::RenderJson() {
gpr_cycle_counter_to_time(
last_message_received_cycle_.Load(MemoryOrder::RELAXED)),
GPR_CLOCK_REALTIME);
char* ts_str = gpr_format_timespec(ts);
data["lastMessageReceivedTimestamp"] = ts_str;
gpr_free(ts_str);
data["lastMessageReceivedTimestamp"] = gpr_format_timespec(ts);
}
int64_t keepalives_sent = keepalives_sent_.Load(MemoryOrder::RELAXED);
if (keepalives_sent != 0) {

@ -30,7 +30,6 @@
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include <inttypes.h>
#include <stdarg.h>
@ -39,6 +38,8 @@
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
#include <string>
#include "absl/strings/str_format.h"
static long sys_gettid(void) { return syscall(__NR_gettid); }
@ -63,7 +64,6 @@ void gpr_log(const char* file, int line, gpr_log_severity severity,
void gpr_default_log(gpr_log_func_args* args) {
const char* final_slash;
char* prefix;
const char* display_file;
char time_buffer[64];
time_t timer;
@ -86,12 +86,10 @@ void gpr_default_log(gpr_log_func_args* args) {
strcpy(time_buffer, "error:strftime");
}
gpr_asprintf(&prefix, "%s%s.%09" PRId32 " %7ld %s:%d]",
gpr_log_severity_string(args->severity), time_buffer,
now.tv_nsec, tid, display_file, args->line);
fprintf(stderr, "%-60s %s\n", prefix, args->message);
gpr_free(prefix);
std::string prefix = absl::StrFormat(
"%s%s.%09" PRId32 " %7ld %s:%d]", gpr_log_severity_string(args->severity),
time_buffer, now.tv_nsec, tid, display_file, args->line);
fprintf(stderr, "%-60s %s\n", prefix.c_str(), args->message);
}
#endif /* GPR_LINUX_LOG */

@ -22,7 +22,6 @@
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include <inttypes.h>
#include <pthread.h>
@ -30,6 +29,8 @@
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <string>
#include "absl/strings/str_format.h"
static intptr_t sys_gettid(void) { return (intptr_t)pthread_self(); }
@ -83,13 +84,10 @@ void gpr_default_log(gpr_log_func_args* args) {
strcpy(time_buffer, "error:strftime");
}
char* prefix;
gpr_asprintf(&prefix, "%s%s.%09d %7" PRIdPTR " %s:%d]",
gpr_log_severity_string(args->severity), time_buffer,
(int)(now.tv_nsec), sys_gettid(), display_file, args->line);
fprintf(stderr, "%-70s %s\n", prefix, args->message);
gpr_free(prefix);
std::string prefix = absl::StrFormat(
"%s%s.%09d %7" PRIdPTR " %s:%d]", gpr_log_severity_string(args->severity),
time_buffer, (int)(now.tv_nsec), sys_gettid(), display_file, args->line);
fprintf(stderr, "%-70s %s\n", prefix.c_str(), args->message);
}
#endif /* defined(GPR_POSIX_LOG) */

@ -28,6 +28,8 @@
#include <string.h>
#include <time.h>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
@ -50,12 +52,7 @@ char* gpr_strdup(const char* src) {
return dst;
}
struct dump_out {
size_t capacity;
size_t length;
char* data;
};
char* gpr_format_timespec(gpr_timespec tm) {
std::string gpr_format_timespec(gpr_timespec tm) {
char time_buffer[35];
char ns_buffer[11]; // '.' + 9 digits of precision
struct tm* tm_info = localtime((const time_t*)&tm.tv_sec);
@ -76,11 +73,15 @@ char* gpr_format_timespec(gpr_timespec tm) {
break;
}
}
char* full_time_str;
gpr_asprintf(&full_time_str, "%s%sZ", time_buffer, ns_buffer);
return full_time_str;
return absl::StrCat(time_buffer, ns_buffer, "Z");
}
struct dump_out {
size_t capacity;
size_t length;
char* data;
};
static dump_out dump_out_create(void) {
dump_out r = {0, 0, nullptr};
return r;

@ -26,6 +26,8 @@
#include <stdbool.h>
#include <stddef.h>
#include <string>
/* String utility functions */
/* Flags for gpr_dump function. */
@ -88,13 +90,13 @@ char* gpr_strjoin_sep(const char** strs, size_t nstrs, const char* sep,
void gpr_string_split(const char* input, const char* sep, char*** strs,
size_t* nstrs);
/* Returns an allocated string that represents tm according to RFC-3339, and,
/* Returns a string that represents tm according to RFC-3339, and,
more specifically, follows:
https://developers.google.com/protocol-buffers/docs/proto3#json
Uses RFC 3339, where generated output will always be Z-normalized and uses
0, 3, 6 or 9 fractional digits. */
char* gpr_format_timespec(gpr_timespec);
std::string gpr_format_timespec(gpr_timespec);
/** Case insensitive string comparison... return <0 if lower(a)<lower(b), ==0 if
lower(a)==lower(b), >0 if lower(a)>lower(b) */

@ -30,6 +30,10 @@
#include <ctype.h>
#include <string.h>
#include <string>
#include "absl/strings/str_format.h"
namespace grpc_core {
namespace {
@ -42,12 +46,10 @@ GlobalConfigEnvErrorFunctionType g_global_config_env_error_func =
DefaultGlobalConfigEnvErrorFunction;
void LogParsingError(const char* name, const char* value) {
char* error_message;
gpr_asprintf(&error_message,
"Illegal value '%s' specified for environment variable '%s'",
value, name);
(*g_global_config_env_error_func)(error_message);
gpr_free(error_message);
std::string error_message = absl::StrFormat(
"Illegal value '%s' specified for environment variable '%s'", value,
name);
(*g_global_config_env_error_func)(error_message.c_str());
}
} // namespace

@ -22,6 +22,10 @@
#include <string.h>
#include <string>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
@ -112,11 +116,11 @@ static void append_error(internal_request* req, grpc_error* error) {
GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed HTTP/1 client request");
}
grpc_resolved_address* addr = &req->addresses->addrs[req->next_address - 1];
grpc_core::UniquePtr<char> addr_text(grpc_sockaddr_to_uri(addr));
std::string addr_text = grpc_sockaddr_to_uri(addr);
req->overall_error = grpc_error_add_child(
req->overall_error,
grpc_error_set_str(error, GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_moved_string(std::move(addr_text))));
grpc_slice_from_cpp_string(std::move(addr_text))));
}
static void do_read(internal_request* req) {
@ -266,15 +270,14 @@ void grpc_httpcli_get(grpc_httpcli_context* context,
grpc_resource_quota* resource_quota,
const grpc_httpcli_request* request, grpc_millis deadline,
grpc_closure* on_done, grpc_httpcli_response* response) {
char* name;
if (g_get_override && g_get_override(request, deadline, on_done, response)) {
return;
}
gpr_asprintf(&name, "HTTP:GET:%s:%s", request->host, request->http.path);
std::string name =
absl::StrFormat("HTTP:GET:%s:%s", request->host, request->http.path);
internal_request_begin(context, pollent, resource_quota, request, deadline,
on_done, response, name,
on_done, response, name.c_str(),
grpc_httpcli_format_get_request(request));
gpr_free(name);
}
void grpc_httpcli_post(grpc_httpcli_context* context,
@ -284,16 +287,16 @@ void grpc_httpcli_post(grpc_httpcli_context* context,
const char* body_bytes, size_t body_size,
grpc_millis deadline, grpc_closure* on_done,
grpc_httpcli_response* response) {
char* name;
if (g_post_override && g_post_override(request, body_bytes, body_size,
deadline, on_done, response)) {
return;
}
gpr_asprintf(&name, "HTTP:POST:%s:%s", request->host, request->http.path);
std::string name =
absl::StrFormat("HTTP:POST:%s:%s", request->host, request->http.path);
internal_request_begin(
context, pollent, resource_quota, request, deadline, on_done, response,
name, grpc_httpcli_format_post_request(request, body_bytes, body_size));
gpr_free(name);
name.c_str(),
grpc_httpcli_format_post_request(request, body_bytes, body_size));
}
void grpc_httpcli_set_override(grpc_httpcli_get_override get,

@ -22,6 +22,7 @@
#include <string.h>
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include <grpc/support/alloc.h>
@ -95,11 +96,10 @@ class grpc_httpcli_ssl_channel_security_connector final
/* Check the peer name. */
if (secure_peer_name_ != nullptr &&
!tsi_ssl_peer_matches_name(&peer, secure_peer_name_)) {
char* msg;
gpr_asprintf(&msg, "Peer name %s is not in peer certificate",
secure_peer_name_);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Peer name ", secure_peer_name_,
" is not in peer certificate")
.c_str());
}
grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);
tsi_peer_destruct(&peer);

@ -32,9 +32,12 @@
#include <sys/socket.h>
#include <sys/types.h>
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/iomgr/tcp_posix.h"
@ -53,19 +56,16 @@ grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char* name,
grpc_channel_args* args) {
int sv[2];
grpc_endpoint_pair p;
char* final_name;
create_sockets(sv);
grpc_core::ExecCtx exec_ctx;
gpr_asprintf(&final_name, "%s:client", name);
p.client = grpc_tcp_create(grpc_fd_create(sv[1], final_name, false), args,
"socketpair-server");
gpr_free(final_name);
gpr_asprintf(&final_name, "%s:server", name);
p.server = grpc_tcp_create(grpc_fd_create(sv[0], final_name, false), args,
"socketpair-client");
gpr_free(final_name);
std::string final_name = absl::StrCat(name, ":client");
p.client = grpc_tcp_create(grpc_fd_create(sv[1], final_name.c_str(), false),
args, "socketpair-server");
final_name = absl::StrCat(name, ":server");
p.server = grpc_tcp_create(grpc_fd_create(sv[0], final_name.c_str(), false),
args, "socketpair-client");
return p;
}

@ -19,10 +19,13 @@
#include <grpc/support/port_platform.h>
#ifdef GRPC_CFSTREAM
#include <string>
#include "absl/strings/str_format.h"
#include <CoreFoundation/CoreFoundation.h>
#include <grpc/support/alloc.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/iomgr/error.h"
@ -33,7 +36,6 @@ grpc_error* grpc_error_create_from_cferror(const char* file, int line,
CFErrorRef error = static_cast<CFErrorRef>(arg);
char buf_domain[MAX_ERROR_DESCRIPTION];
char buf_desc[MAX_ERROR_DESCRIPTION];
char* error_msg;
CFErrorDomain domain = CFErrorGetDomain((error));
CFIndex code = CFErrorGetCode((error));
CFStringRef desc = CFErrorCopyDescription((error));
@ -41,12 +43,11 @@ grpc_error* grpc_error_create_from_cferror(const char* file, int line,
kCFStringEncodingUTF8);
CFStringGetCString(desc, buf_desc, MAX_ERROR_DESCRIPTION,
kCFStringEncodingUTF8);
gpr_asprintf(&error_msg, "%s (error domain:%s, code:%ld, description:%s)",
custom_desc, buf_domain, code, buf_desc);
std::string error_msg =
absl::StrFormat("%s (error domain:%s, code:%ld, description:%s)",
custom_desc, buf_domain, code, buf_desc);
CFRelease(desc);
grpc_error* return_error = grpc_error_create(
file, line, grpc_slice_from_copied_string(error_msg), NULL, 0);
gpr_free(error_msg);
return return_error;
return grpc_error_create(
file, line, grpc_slice_from_copied_string(error_msg.c_str()), NULL, 0);
}
#endif /* GRPC_CFSTREAM */

@ -38,14 +38,15 @@
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include <grpc/support/alloc.h>
#include <grpc/support/cpu.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/gpr/string.h"
@ -351,16 +352,14 @@ static grpc_fd* fd_create(int fd, const char* name, bool track_err) {
new_fd->freelist_next = nullptr;
char* fd_name;
gpr_asprintf(&fd_name, "%s fd=%d", name, fd);
grpc_iomgr_register_object(&new_fd->iomgr_object, fd_name);
std::string fd_name = absl::StrCat(name, " fd=", fd);
grpc_iomgr_register_object(&new_fd->iomgr_object, fd_name.c_str());
fork_fd_list_add_grpc_fd(new_fd);
#ifndef NDEBUG
if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
gpr_log(GPR_DEBUG, "FD %d %p create %s", fd, new_fd, fd_name);
gpr_log(GPR_DEBUG, "FD %d %p create %s", fd, new_fd, fd_name.c_str());
}
#endif
gpr_free(fd_name);
struct epoll_event ev;
ev.events = static_cast<uint32_t>(EPOLLIN | EPOLLOUT | EPOLLET);

@ -38,10 +38,14 @@
#include <sys/syscall.h>
#include <unistd.h>
#include <grpc/support/alloc.h>
#include <grpc/support/string_util.h>
#include <string>
#include "absl/container/inlined_vector.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/gpr/spinlock.h"
#include "src/core/lib/gpr/tls.h"
@ -124,11 +128,10 @@ static const char* pollable_type_string(pollable_type t) {
return "<invalid>";
}
static char* pollable_desc(pollable* p) {
char* out;
gpr_asprintf(&out, "type=%s epfd=%d wakeup=%d", pollable_type_string(p->type),
p->epfd, p->wakeup.read_fd);
return out;
static std::string pollable_desc(pollable* p) {
return absl::StrFormat("type=%s epfd=%d wakeup=%d",
pollable_type_string(p->type), p->epfd,
p->wakeup.read_fd);
}
/// Shared empty pollable - used by pollset to poll on until the first fd is
@ -170,15 +173,13 @@ struct grpc_fd {
write_closure.InitEvent();
error_closure.InitEvent();
char* fd_name;
gpr_asprintf(&fd_name, "%s fd=%d", name, fd);
grpc_iomgr_register_object(&iomgr_object, fd_name);
std::string fd_name = absl::StrCat(name, " fd=", fd);
grpc_iomgr_register_object(&iomgr_object, fd_name.c_str());
#ifndef NDEBUG
if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) {
gpr_log(GPR_DEBUG, "FD %d %p create %s", fd, this, fd_name);
gpr_log(GPR_DEBUG, "FD %d %p create %s", fd, this, fd_name.c_str());
}
#endif
gpr_free(fd_name);
}
// This is really the dtor, but the poller threads waking up from
@ -934,9 +935,8 @@ static grpc_error* pollable_epoll(pollable* p, grpc_millis deadline) {
int timeout = poll_deadline_to_millis_timeout(deadline);
if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
char* desc = pollable_desc(p);
gpr_log(GPR_INFO, "POLLABLE:%p[%s] poll for %dms", p, desc, timeout);
gpr_free(desc);
gpr_log(GPR_INFO, "POLLABLE:%p[%s] poll for %dms", p,
pollable_desc(p).c_str(), timeout);
}
if (timeout != 0) {

@ -32,9 +32,12 @@
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/gpr/murmur_hash.h"
@ -381,10 +384,8 @@ static grpc_fd* fd_create(int fd, const char* name, bool track_err) {
r->released = 0;
gpr_atm_no_barrier_store(&r->pollhup, 0);
char* name2;
gpr_asprintf(&name2, "%s fd=%d", name, fd);
grpc_iomgr_register_object(&r->iomgr_object, name2);
gpr_free(name2);
std::string name2 = absl::StrCat(name, " fd=", fd);
grpc_iomgr_register_object(&r->iomgr_object, name2.c_str());
fork_fd_list_add_grpc_fd(r);
return r;
}

@ -18,22 +18,24 @@
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
#include "src/core/lib/iomgr/resolve_address_custom.h"
#include <grpc/support/alloc.h>
#include <grpc/support/string_util.h>
#include <string.h>
#include <string>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/iomgr/iomgr_custom.h"
#include "src/core/lib/iomgr/resolve_address_custom.h"
#include "src/core/lib/iomgr/port.h"
#include "src/core/lib/iomgr/sockaddr_utils.h"
#include <string.h>
struct grpc_custom_resolver {
grpc_closure* on_done = nullptr;
grpc_resolved_addresses** addresses = nullptr;
@ -88,23 +90,16 @@ static grpc_error* try_split_host_port(const char* name,
const char* default_port,
std::string* host, std::string* port) {
/* parse name, splitting it into host and port parts */
grpc_error* error;
grpc_core::SplitHostPort(name, host, port);
if (host->empty()) {
char* msg;
gpr_asprintf(&msg, "unparseable host:port: '%s'", name);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return error;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("unparseable host:port: '%s'", name).c_str());
}
if (port->empty()) {
// TODO(murgatroid99): add tests for this case
if (default_port == nullptr) {
char* msg;
gpr_asprintf(&msg, "no port in name '%s'", name);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return error;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("no port in name '%s'", name).c_str());
}
*port = default_port;
}

@ -29,6 +29,10 @@
#include <string.h>
#include <sys/types.h>
#include <string>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/log_windows.h>
@ -65,18 +69,14 @@ static grpc_error* windows_blocking_resolve_address(
std::string port;
grpc_core::SplitHostPort(name, &host, &port);
if (host.empty()) {
char* msg;
gpr_asprintf(&msg, "unparseable host:port: '%s'", name);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("unparseable host:port: '%s'", name).c_str());
goto done;
}
if (port.empty()) {
if (default_port == NULL) {
char* msg;
gpr_asprintf(&msg, "no port in name '%s'", name);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("no port in name '%s'", name).c_str());
goto done;
}
port = default_port;

@ -25,10 +25,13 @@
#include <stdint.h>
#include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/slice_buffer.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/iomgr/combiner.h"
@ -118,7 +121,7 @@ struct grpc_resource_user {
grpc_resource_user_link links[GRPC_RULIST_COUNT];
/* The name of this resource user, for debugging/tracing */
char* name;
std::string name;
};
struct grpc_resource_quota {
@ -181,7 +184,7 @@ struct grpc_resource_quota {
/* Roots of all resource user lists */
grpc_resource_user* roots[GRPC_RULIST_COUNT];
char* name;
std::string name;
};
static void ru_unref_by(grpc_resource_user* resource_user, gpr_atm amount);
@ -349,13 +352,13 @@ static bool rq_alloc(grpc_resource_quota* resource_quota) {
gpr_log(GPR_INFO,
"RQ %s %s: grant alloc %" PRId64
" bytes; rq_free_pool -> %" PRId64,
resource_quota->name, resource_user->name, amt,
resource_quota->name.c_str(), resource_user->name.c_str(), amt,
resource_quota->free_pool);
}
} else if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace) &&
resource_user->free_pool >= 0) {
gpr_log(GPR_INFO, "RQ %s %s: discard already satisfied alloc request",
resource_quota->name, resource_user->name);
resource_quota->name.c_str(), resource_user->name.c_str());
}
if (resource_user->free_pool >= 0) {
resource_user->allocating = false;
@ -388,7 +391,7 @@ static bool rq_reclaim_from_per_user_free_pool(
gpr_log(GPR_INFO,
"RQ %s %s: reclaim_from_per_user_free_pool %" PRId64
" bytes; rq_free_pool -> %" PRId64,
resource_quota->name, resource_user->name, amt,
resource_quota->name.c_str(), resource_user->name.c_str(), amt,
resource_quota->free_pool);
}
gpr_mu_unlock(&resource_user->mu);
@ -398,7 +401,7 @@ static bool rq_reclaim_from_per_user_free_pool(
gpr_log(GPR_INFO,
"RQ %s %s: failed to reclaim_from_per_user_free_pool; "
"free_pool = %" PRId64 "; rq_free_pool = %" PRId64,
resource_quota->name, resource_user->name,
resource_quota->name.c_str(), resource_user->name.c_str(),
resource_user->free_pool, resource_quota->free_pool);
}
gpr_mu_unlock(&resource_user->mu);
@ -415,8 +418,9 @@ static bool rq_reclaim(grpc_resource_quota* resource_quota, bool destructive) {
grpc_resource_user* resource_user = rulist_pop_head(resource_quota, list);
if (resource_user == nullptr) return false;
if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO, "RQ %s %s: initiate %s reclamation", resource_quota->name,
resource_user->name, destructive ? "destructive" : "benign");
gpr_log(GPR_INFO, "RQ %s %s: initiate %s reclamation",
resource_quota->name.c_str(), resource_user->name.c_str(),
destructive ? "destructive" : "benign");
}
resource_quota->reclaiming = true;
grpc_resource_quota_ref_internal(resource_quota);
@ -585,8 +589,7 @@ static void ru_destroy(void* ru, grpc_error* /*error*/) {
}
grpc_resource_quota_unref_internal(resource_user->resource_quota);
gpr_mu_destroy(&resource_user->mu);
gpr_free(resource_user->name);
gpr_free(resource_user);
delete resource_user;
}
static void ru_alloc_slices(
@ -640,8 +643,7 @@ static void rq_reclamation_done(void* rq, grpc_error* /*error*/) {
/* Public API */
grpc_resource_quota* grpc_resource_quota_create(const char* name) {
grpc_resource_quota* resource_quota =
static_cast<grpc_resource_quota*>(gpr_malloc(sizeof(*resource_quota)));
grpc_resource_quota* resource_quota = new grpc_resource_quota;
gpr_ref_init(&resource_quota->refs, 1);
resource_quota->combiner = grpc_combiner_create();
resource_quota->free_pool = INT64_MAX;
@ -655,10 +657,10 @@ grpc_resource_quota* grpc_resource_quota_create(const char* name) {
resource_quota->reclaiming = false;
gpr_atm_no_barrier_store(&resource_quota->memory_usage_estimation, 0);
if (name != nullptr) {
resource_quota->name = gpr_strdup(name);
resource_quota->name = name;
} else {
gpr_asprintf(&resource_quota->name, "anonymous_pool_%" PRIxPTR,
(intptr_t)resource_quota);
resource_quota->name =
absl::StrCat("anonymous_pool_", (intptr_t)resource_quota);
}
GRPC_CLOSURE_INIT(&resource_quota->rq_step_closure, rq_step, resource_quota,
nullptr);
@ -675,9 +677,8 @@ void grpc_resource_quota_unref_internal(grpc_resource_quota* resource_quota) {
// No outstanding thread quota
GPR_ASSERT(resource_quota->num_threads_allocated == 0);
GRPC_COMBINER_UNREF(resource_quota->combiner, "resource_quota");
gpr_free(resource_quota->name);
gpr_mu_destroy(&resource_quota->thread_count_mu);
gpr_free(resource_quota);
delete resource_quota;
}
}
@ -774,8 +775,7 @@ const grpc_arg_pointer_vtable* grpc_resource_quota_arg_vtable(void) {
grpc_resource_user* grpc_resource_user_create(
grpc_resource_quota* resource_quota, const char* name) {
grpc_resource_user* resource_user =
static_cast<grpc_resource_user*>(gpr_malloc(sizeof(*resource_user)));
grpc_resource_user* resource_user = new grpc_resource_user;
resource_user->resource_quota =
grpc_resource_quota_ref_internal(resource_quota);
GRPC_CLOSURE_INIT(&resource_user->allocate_closure, &ru_allocate,
@ -805,10 +805,10 @@ grpc_resource_user* grpc_resource_user_create(
resource_user->links[i].next = resource_user->links[i].prev = nullptr;
}
if (name != nullptr) {
resource_user->name = gpr_strdup(name);
resource_user->name = name;
} else {
gpr_asprintf(&resource_user->name, "anonymous_resource_user_%" PRIxPTR,
(intptr_t)resource_user);
resource_user->name =
absl::StrCat("anonymous_resource_user_", (intptr_t)resource_user);
}
return resource_user;
}
@ -890,8 +890,8 @@ static bool resource_user_alloc_locked(grpc_resource_user* resource_user,
resource_user->free_pool -= static_cast<int64_t>(size);
if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO, "RQ %s %s: alloc %" PRIdPTR "; free_pool -> %" PRId64,
resource_user->resource_quota->name, resource_user->name, size,
resource_user->free_pool);
resource_user->resource_quota->name.c_str(),
resource_user->name.c_str(), size, resource_user->free_pool);
}
if (GPR_LIKELY(resource_user->free_pool >= 0)) return true;
// Slow path: We need to wait for the free pool to refill.
@ -951,8 +951,8 @@ void grpc_resource_user_free(grpc_resource_user* resource_user, size_t size) {
resource_user->free_pool += static_cast<int64_t>(size);
if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO, "RQ %s %s: free %" PRIdPTR "; free_pool -> %" PRId64,
resource_user->resource_quota->name, resource_user->name, size,
resource_user->free_pool);
resource_user->resource_quota->name.c_str(),
resource_user->name.c_str(), size, resource_user->free_pool);
}
bool is_bigger_than_zero = resource_user->free_pool > 0;
if (is_bigger_than_zero && was_zero_or_negative &&
@ -977,7 +977,8 @@ void grpc_resource_user_post_reclaimer(grpc_resource_user* resource_user,
void grpc_resource_user_finish_reclamation(grpc_resource_user* resource_user) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
gpr_log(GPR_INFO, "RQ %s %s: reclamation complete",
resource_user->resource_quota->name, resource_user->name);
resource_user->resource_quota->name.c_str(),
resource_user->name.c_str());
}
resource_user->resource_quota->combiner->Run(
&resource_user->resource_quota->rq_reclamation_done_closure,

@ -24,11 +24,13 @@
#include <inttypes.h>
#include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/host_port.h"
@ -212,8 +214,8 @@ void grpc_string_to_sockaddr(grpc_resolved_address* out, char* addr, int port) {
grpc_sockaddr_set_port(out, port);
}
char* grpc_sockaddr_to_uri(const grpc_resolved_address* resolved_addr) {
if (resolved_addr->len == 0) return nullptr;
std::string grpc_sockaddr_to_uri(const grpc_resolved_address* resolved_addr) {
if (resolved_addr->len == 0) return "";
grpc_resolved_address addr_normalized;
if (grpc_sockaddr_is_v4mapped(resolved_addr, &addr_normalized)) {
resolved_addr = &addr_normalized;
@ -224,9 +226,9 @@ char* grpc_sockaddr_to_uri(const grpc_resolved_address* resolved_addr) {
}
std::string path =
grpc_sockaddr_to_string(resolved_addr, false /* normalize */);
char* uri_str = nullptr;
std::string uri_str;
if (scheme != nullptr) {
gpr_asprintf(&uri_str, "%s:%s", scheme, path.c_str());
uri_str = absl::StrCat(scheme, ":", path);
}
return uri_str;
}

@ -69,7 +69,7 @@ std::string grpc_sockaddr_to_string(const grpc_resolved_address* addr,
void grpc_string_to_sockaddr(grpc_resolved_address* out, char* addr, int port);
/* Returns the URI string corresponding to \a addr */
char* grpc_sockaddr_to_uri(const grpc_resolved_address* addr);
std::string grpc_sockaddr_to_uri(const grpc_resolved_address* addr);
/* Returns the URI scheme corresponding to \a addr */
const char* grpc_sockaddr_get_uri_scheme(const grpc_resolved_address* addr);

@ -27,10 +27,11 @@
// must be included after winsock2.h
#include <mswsock.h>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/log_windows.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/iomgr/iocp_windows.h"
#include "src/core/lib/iomgr/iomgr_internal.h"
@ -42,14 +43,12 @@
static DWORD s_wsa_socket_flags;
grpc_winsocket* grpc_winsocket_create(SOCKET socket, const char* name) {
char* final_name;
grpc_winsocket* r = (grpc_winsocket*)gpr_malloc(sizeof(grpc_winsocket));
memset(r, 0, sizeof(grpc_winsocket));
r->socket = socket;
gpr_mu_init(&r->state_mu);
gpr_asprintf(&final_name, "%s:socket=0x%p", name, r);
grpc_iomgr_register_object(&r->iomgr_object, final_name);
gpr_free(final_name);
grpc_iomgr_register_object(
&r->iomgr_object, absl::StrFormat("%s:socket=0x%p", name, r).c_str());
grpc_iocp_add_socket(r);
return r;
}

@ -46,7 +46,7 @@
extern grpc_core::TraceFlag grpc_tcp_trace;
typedef struct CFStreamConnect {
struct CFStreamConnect {
gpr_mu mu;
gpr_refcount refcount;
@ -65,9 +65,9 @@ typedef struct CFStreamConnect {
grpc_closure* closure;
grpc_endpoint** endpoint;
int refs;
char* addr_name;
std::string addr_name;
grpc_resource_quota* resource_quota;
} CFStreamConnect;
};
static void CFStreamConnectCleanup(CFStreamConnect* connect) {
grpc_resource_quota_unref_internal(connect->resource_quota);
@ -75,8 +75,7 @@ static void CFStreamConnectCleanup(CFStreamConnect* connect) {
CFRelease(connect->read_stream);
CFRelease(connect->write_stream);
gpr_mu_destroy(&connect->mu);
gpr_free(connect->addr_name);
gpr_free(connect);
delete connect;
}
static void OnAlarm(void* arg, grpc_error* error) {
@ -130,8 +129,9 @@ static void OnOpen(void* arg, grpc_error* error) {
}
if (error == GRPC_ERROR_NONE) {
*endpoint = grpc_cfstream_endpoint_create(
connect->read_stream, connect->write_stream, connect->addr_name,
connect->resource_quota, connect->stream_handle);
connect->read_stream, connect->write_stream,
connect->addr_name.c_str(), connect->resource_quota,
connect->stream_handle);
}
} else {
GRPC_ERROR_REF(error);
@ -157,9 +157,7 @@ static void CFStreamClientConnect(grpc_closure* closure, grpc_endpoint** ep,
const grpc_channel_args* channel_args,
const grpc_resolved_address* resolved_addr,
grpc_millis deadline) {
CFStreamConnect* connect;
connect = (CFStreamConnect*)gpr_zalloc(sizeof(CFStreamConnect));
CFStreamConnect* connect = new CFStreamConnect();
connect->closure = closure;
connect->endpoint = ep;
connect->addr_name = grpc_sockaddr_to_uri(resolved_addr);
@ -170,7 +168,7 @@ static void CFStreamClientConnect(grpc_closure* closure, grpc_endpoint** ep,
if (grpc_tcp_trace.enabled()) {
gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %p, %s: asynchronously connecting",
connect, connect->addr_name);
connect, connect->addr_name.c_str());
}
grpc_resource_quota* resource_quota = grpc_resource_quota_create(NULL);

@ -42,15 +42,14 @@ struct grpc_custom_tcp_connect {
grpc_closure* closure;
grpc_endpoint** endpoint;
int refs;
char* addr_name;
std::string addr_name;
grpc_resource_quota* resource_quota;
};
static void custom_tcp_connect_cleanup(grpc_custom_tcp_connect* connect) {
grpc_custom_socket* socket = connect->socket;
grpc_resource_quota_unref_internal(connect->resource_quota);
gpr_free(connect->addr_name);
gpr_free(connect);
delete connect;
socket->refs--;
if (socket->refs == 0) {
grpc_custom_socket_vtable->destroy(socket);
@ -67,7 +66,7 @@ static void on_alarm(void* acp, grpc_error* error) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
const char* str = grpc_error_string(error);
gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_alarm: error=%s",
connect->addr_name, str);
connect->addr_name.c_str(), str);
}
if (error == GRPC_ERROR_NONE) {
/* error == NONE implies that the timer ran out, and wasn't cancelled. If
@ -89,7 +88,7 @@ static void custom_connect_callback_internal(grpc_custom_socket* socket,
grpc_timer_cancel(&connect->alarm);
if (error == GRPC_ERROR_NONE) {
*connect->endpoint = custom_tcp_endpoint_create(
socket, connect->resource_quota, connect->addr_name);
socket, connect->resource_quota, connect->addr_name.c_str());
}
done = (--connect->refs == 0);
if (done) {
@ -120,7 +119,6 @@ static void tcp_connect(grpc_closure* closure, grpc_endpoint** ep,
GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
(void)channel_args;
(void)interested_parties;
grpc_custom_tcp_connect* connect;
grpc_resource_quota* resource_quota = grpc_resource_quota_create(nullptr);
if (channel_args != nullptr) {
for (size_t i = 0; i < channel_args->num_args; i++) {
@ -135,8 +133,7 @@ static void tcp_connect(grpc_closure* closure, grpc_endpoint** ep,
(grpc_custom_socket*)gpr_malloc(sizeof(grpc_custom_socket));
socket->refs = 2;
grpc_custom_socket_vtable->init(socket, GRPC_AF_UNSPEC);
connect =
(grpc_custom_tcp_connect*)gpr_malloc(sizeof(grpc_custom_tcp_connect));
grpc_custom_tcp_connect* connect = new grpc_custom_tcp_connect();
connect->closure = closure;
connect->endpoint = ep;
connect->addr_name = grpc_sockaddr_to_uri(resolved_addr);
@ -149,7 +146,7 @@ static void tcp_connect(grpc_closure* closure, grpc_endpoint** ep,
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "CLIENT_CONNECT: %p %s: asynchronously connecting",
socket, connect->addr_name);
socket, connect->addr_name.c_str());
}
GRPC_CLOSURE_INIT(&connect->on_alarm, on_alarm, socket,

@ -29,9 +29,10 @@
#include <string.h>
#include <unistd.h>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include "src/core/lib/channel/channel_args.h"
@ -57,11 +58,12 @@ struct async_connect {
int refs;
grpc_closure write_closure;
grpc_pollset_set* interested_parties;
char* addr_str;
std::string addr_str;
grpc_endpoint** ep;
grpc_closure* closure;
grpc_channel_args* channel_args;
};
static grpc_error* prepare_socket(const grpc_resolved_address* addr, int fd,
const grpc_channel_args* channel_args) {
grpc_error* err = GRPC_ERROR_NONE;
@ -102,8 +104,8 @@ static void tc_on_alarm(void* acp, grpc_error* error) {
async_connect* ac = static_cast<async_connect*>(acp);
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
const char* str = grpc_error_string(error);
gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_alarm: error=%s", ac->addr_str,
str);
gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_alarm: error=%s",
ac->addr_str.c_str(), str);
}
gpr_mu_lock(&ac->mu);
if (ac->fd != nullptr) {
@ -114,9 +116,8 @@ static void tc_on_alarm(void* acp, grpc_error* error) {
gpr_mu_unlock(&ac->mu);
if (done) {
gpr_mu_destroy(&ac->mu);
gpr_free(ac->addr_str);
grpc_channel_args_destroy(ac->channel_args);
gpr_free(ac);
delete ac;
}
}
@ -139,8 +140,8 @@ static void on_writable(void* acp, grpc_error* error) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
const char* str = grpc_error_string(error);
gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_writable: error=%s", ac->addr_str,
str);
gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: on_writable: error=%s",
ac->addr_str.c_str(), str);
}
gpr_mu_lock(&ac->mu);
@ -172,7 +173,8 @@ static void on_writable(void* acp, grpc_error* error) {
switch (so_error) {
case 0:
grpc_pollset_set_del_fd(ac->interested_parties, fd);
*ep = grpc_tcp_client_create_from_fd(fd, ac->channel_args, ac->addr_str);
*ep = grpc_tcp_client_create_from_fd(fd, ac->channel_args,
ac->addr_str.c_str());
fd = nullptr;
break;
case ENOBUFS:
@ -214,19 +216,17 @@ finish:
done = (--ac->refs == 0);
// Create a copy of the data from "ac" to be accessed after the unlock, as
// "ac" and its contents may be deallocated by the time they are read.
const grpc_slice addr_str_slice = grpc_slice_from_copied_string(ac->addr_str);
const grpc_slice addr_str_slice = grpc_slice_from_cpp_string(ac->addr_str);
gpr_mu_unlock(&ac->mu);
if (error != GRPC_ERROR_NONE) {
char* error_descr;
grpc_slice str;
bool ret = grpc_error_get_str(error, GRPC_ERROR_STR_DESCRIPTION, &str);
GPR_ASSERT(ret);
char* desc = grpc_slice_to_c_string(str);
gpr_asprintf(&error_descr, "Failed to connect to remote host: %s", desc);
error = grpc_error_set_str(error, GRPC_ERROR_STR_DESCRIPTION,
grpc_slice_from_copied_string(error_descr));
gpr_free(error_descr);
gpr_free(desc);
std::string description = absl::StrCat("Failed to connect to remote host: ",
grpc_core::StringViewFromSlice(str));
error =
grpc_error_set_str(error, GRPC_ERROR_STR_DESCRIPTION,
grpc_slice_from_cpp_string(std::move(description)));
error = grpc_error_set_str(error, GRPC_ERROR_STR_TARGET_ADDRESS,
addr_str_slice /* takes ownership */);
} else {
@ -236,9 +236,8 @@ finish:
// This is safe even outside the lock, because "done", the sentinel, is
// populated *inside* the lock.
gpr_mu_destroy(&ac->mu);
gpr_free(ac->addr_str);
grpc_channel_args_destroy(ac->channel_args);
gpr_free(ac);
delete ac;
}
grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
}
@ -279,33 +278,25 @@ void grpc_tcp_client_create_from_prepared_fd(
const grpc_channel_args* channel_args, const grpc_resolved_address* addr,
grpc_millis deadline, grpc_endpoint** ep) {
int err;
async_connect* ac;
do {
err = connect(fd, reinterpret_cast<const grpc_sockaddr*>(addr->addr),
addr->len);
} while (err < 0 && errno == EINTR);
char* name;
char* addr_str;
addr_str = grpc_sockaddr_to_uri(addr);
gpr_asprintf(&name, "tcp-client:%s", addr_str);
grpc_fd* fdobj = grpc_fd_create(fd, name, true);
gpr_free(name);
gpr_free(addr_str);
std::string name = absl::StrCat("tcp-client:", grpc_sockaddr_to_uri(addr));
grpc_fd* fdobj = grpc_fd_create(fd, name.c_str(), true);
if (err >= 0) {
char* addr_str = grpc_sockaddr_to_uri(addr);
*ep = grpc_tcp_client_create_from_fd(fdobj, channel_args, addr_str);
gpr_free(addr_str);
*ep = grpc_tcp_client_create_from_fd(fdobj, channel_args,
grpc_sockaddr_to_uri(addr).c_str());
grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
return;
}
if (errno != EWOULDBLOCK && errno != EINPROGRESS) {
grpc_error* error = GRPC_OS_ERROR(errno, "connect");
char* addr_str = grpc_sockaddr_to_uri(addr);
error = grpc_error_set_str(error, GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_copied_string(addr_str));
gpr_free(addr_str);
error = grpc_error_set_str(
error, GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_cpp_string(grpc_sockaddr_to_uri(addr)));
grpc_fd_orphan(fdobj, nullptr, nullptr, "tcp_client_connect_error");
grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error);
return;
@ -313,7 +304,7 @@ void grpc_tcp_client_create_from_prepared_fd(
grpc_pollset_set_add_fd(interested_parties, fdobj);
ac = static_cast<async_connect*>(gpr_malloc(sizeof(async_connect)));
async_connect* ac = new async_connect();
ac->closure = closure;
ac->ep = ep;
ac->fd = fdobj;
@ -327,7 +318,7 @@ void grpc_tcp_client_create_from_prepared_fd(
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "CLIENT_CONNECT: %s: asynchronously connecting fd %p",
ac->addr_str, fdobj);
ac->addr_str.c_str(), fdobj);
}
gpr_mu_lock(&ac->mu);

@ -39,6 +39,7 @@
#include "src/core/lib/iomgr/tcp_client.h"
#include "src/core/lib/iomgr/tcp_windows.h"
#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/slice/slice_internal.h"
struct async_connect {
grpc_closure* on_done;
@ -46,12 +47,13 @@ struct async_connect {
grpc_winsocket* socket;
grpc_timer alarm;
grpc_closure on_alarm;
char* addr_name;
std::string addr_name;
int refs;
grpc_closure on_connect;
grpc_endpoint** endpoint;
grpc_channel_args* channel_args;
};
static void async_connect_unlock_and_cleanup(async_connect* ac,
grpc_winsocket* socket) {
int done = (--ac->refs == 0);
@ -59,8 +61,7 @@ static void async_connect_unlock_and_cleanup(async_connect* ac,
if (done) {
grpc_channel_args_destroy(ac->channel_args);
gpr_mu_destroy(&ac->mu);
gpr_free(ac->addr_name);
gpr_free(ac);
delete ac;
}
if (socket != NULL) grpc_winsocket_destroy(socket);
}
@ -105,7 +106,7 @@ static void on_connect(void* acp, grpc_error* error) {
error = GRPC_WSA_ERROR(WSAGetLastError(), "ConnectEx");
closesocket(socket->socket);
} else {
*ep = grpc_tcp_create(socket, ac->channel_args, ac->addr_name);
*ep = grpc_tcp_create(socket, ac->channel_args, ac->addr_name.c_str());
socket = NULL;
}
} else {
@ -131,13 +132,13 @@ static void tcp_connect(grpc_closure* on_done, grpc_endpoint** endpoint,
int status;
grpc_resolved_address addr6_v4mapped;
grpc_resolved_address local_address;
async_connect* ac;
grpc_winsocket* socket = NULL;
LPFN_CONNECTEX ConnectEx;
GUID guid = WSAID_CONNECTEX;
DWORD ioctl_num_bytes;
grpc_winsocket_callback_info* info;
grpc_error* error = GRPC_ERROR_NONE;
async_connect* ac = NULL;
*endpoint = NULL;
@ -194,7 +195,7 @@ static void tcp_connect(grpc_closure* on_done, grpc_endpoint** endpoint,
}
}
ac = (async_connect*)gpr_malloc(sizeof(async_connect));
ac = new async_connect();
ac->on_done = on_done;
ac->socket = socket;
gpr_mu_init(&ac->mu);
@ -211,13 +212,12 @@ static void tcp_connect(grpc_closure* on_done, grpc_endpoint** endpoint,
failure:
GPR_ASSERT(error != GRPC_ERROR_NONE);
char* target_uri = grpc_sockaddr_to_uri(addr);
std::string target_uri = grpc_sockaddr_to_uri(addr);
grpc_error* final_error =
grpc_error_set_str(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Failed to connect", &error, 1),
GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_copied_string(
target_uri == nullptr ? "NULL" : target_uri));
grpc_slice_from_cpp_string(std::move(target_uri)));
GRPC_ERROR_UNREF(error);
if (socket != NULL) {
grpc_winsocket_destroy(socket);

@ -345,7 +345,7 @@ static grpc_endpoint_vtable vtable = {endpoint_read,
grpc_endpoint* custom_tcp_endpoint_create(grpc_custom_socket* socket,
grpc_resource_quota* resource_quota,
char* peer_string) {
const char* peer_string) {
custom_tcp_endpoint* tcp =
(custom_tcp_endpoint*)gpr_malloc(sizeof(custom_tcp_endpoint));
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;

@ -79,6 +79,6 @@ void grpc_custom_close_server_callback(grpc_tcp_listener* listener);
grpc_endpoint* custom_tcp_endpoint_create(grpc_custom_socket* socket,
grpc_resource_quota* resource_quota,
char* peer_string);
const char* peer_string);
#endif /* GRPC_CORE_LIB_IOMGR_TCP_CUSTOM_H */

@ -216,10 +216,9 @@ static void finish_accept(grpc_tcp_listener* sp, grpc_custom_socket* socket) {
(grpc_tcp_server_acceptor*)gpr_malloc(sizeof(*acceptor));
grpc_endpoint* ep = nullptr;
grpc_resolved_address peer_name;
char* peer_name_string;
std::string peer_name_string;
grpc_error* err;
peer_name_string = nullptr;
memset(&peer_name, 0, sizeof(grpc_resolved_address));
peer_name.len = GRPC_MAX_SOCKADDR_SIZE;
err = grpc_custom_socket_vtable->getpeername(
@ -231,21 +230,16 @@ static void finish_accept(grpc_tcp_listener* sp, grpc_custom_socket* socket) {
GRPC_ERROR_UNREF(err);
}
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
if (peer_name_string) {
gpr_log(GPR_INFO, "SERVER_CONNECT: %p accepted connection: %s",
sp->server, peer_name_string);
} else {
gpr_log(GPR_INFO, "SERVER_CONNECT: %p accepted connection", sp->server);
}
gpr_log(GPR_INFO, "SERVER_CONNECT: %p accepted connection: %s", sp->server,
peer_name_string.c_str());
}
ep = custom_tcp_endpoint_create(socket, sp->server->resource_quota,
peer_name_string);
peer_name_string.c_str());
acceptor->from_server = sp->server;
acceptor->port_index = sp->port_index;
acceptor->fd_index = 0;
acceptor->external_connection = false;
sp->server->on_accept_cb(sp->server->on_accept_cb_arg, ep, nullptr, acceptor);
gpr_free(peer_name_string);
}
static void custom_accept_callback(grpc_custom_socket* socket,

@ -39,9 +39,11 @@
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/sync.h>
#include <grpc/support/time.h>
@ -196,8 +198,6 @@ static void on_read(void* arg, grpc_error* err) {
/* loop until accept4 returns EAGAIN, and then re-arm notification */
for (;;) {
grpc_resolved_address addr;
char* addr_str;
char* name;
memset(&addr, 0, sizeof(addr));
addr.len = static_cast<socklen_t>(sizeof(struct sockaddr_storage));
/* Note: If we ever decide to return this address to the user, remember to
@ -238,14 +238,14 @@ static void on_read(void* arg, grpc_error* err) {
grpc_set_socket_no_sigpipe_if_possible(fd);
addr_str = grpc_sockaddr_to_uri(&addr);
gpr_asprintf(&name, "tcp-server-connection:%s", addr_str);
std::string addr_str = grpc_sockaddr_to_uri(&addr);
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
gpr_log(GPR_INFO, "SERVER_CONNECT: incoming connection: %s", addr_str);
gpr_log(GPR_INFO, "SERVER_CONNECT: incoming connection: %s",
addr_str.c_str());
}
grpc_fd* fdobj = grpc_fd_create(fd, name, true);
std::string name = absl::StrCat("tcp-server-connection:", addr_str);
grpc_fd* fdobj = grpc_fd_create(fd, name.c_str(), true);
read_notifier_pollset =
sp->server->pollsets[static_cast<size_t>(gpr_atm_no_barrier_fetch_add(
@ -264,11 +264,8 @@ static void on_read(void* arg, grpc_error* err) {
sp->server->on_accept_cb(
sp->server->on_accept_cb_arg,
grpc_tcp_create(fdobj, sp->server->channel_args, addr_str),
grpc_tcp_create(fdobj, sp->server->channel_args, addr_str.c_str()),
read_notifier_pollset, acceptor);
gpr_free(name);
gpr_free(addr_str);
}
GPR_UNREACHABLE_CODE(return );
@ -352,7 +349,6 @@ static grpc_error* add_wildcard_addrs_to_server(grpc_tcp_server* s,
static grpc_error* clone_port(grpc_tcp_listener* listener, unsigned count) {
grpc_tcp_listener* sp = nullptr;
std::string addr_str;
char* name;
grpc_error* err;
for (grpc_tcp_listener* l = listener->next; l && l->is_sibling; l = l->next) {
@ -371,7 +367,6 @@ static grpc_error* clone_port(grpc_tcp_listener* listener, unsigned count) {
if (err != GRPC_ERROR_NONE) return err;
listener->server->nports++;
addr_str = grpc_sockaddr_to_string(&listener->addr, true);
gpr_asprintf(&name, "tcp-server-listener:%s/clone-%d", addr_str.c_str(), i);
sp = static_cast<grpc_tcp_listener*>(gpr_malloc(sizeof(grpc_tcp_listener)));
sp->next = listener->next;
listener->next = sp;
@ -382,7 +377,11 @@ static grpc_error* clone_port(grpc_tcp_listener* listener, unsigned count) {
listener->sibling = sp;
sp->server = listener->server;
sp->fd = fd;
sp->emfd = grpc_fd_create(fd, name, true);
sp->emfd = grpc_fd_create(
fd,
absl::StrFormat("tcp-server-listener:%s/clone-%d", addr_str.c_str(), i)
.c_str(),
true);
memcpy(&sp->addr, &listener->addr, sizeof(grpc_resolved_address));
sp->port = port;
sp->port_index = listener->port_index;
@ -391,7 +390,6 @@ static grpc_error* clone_port(grpc_tcp_listener* listener, unsigned count) {
while (listener->server->tail->next != nullptr) {
listener->server->tail = listener->server->tail->next;
}
gpr_free(name);
}
return GRPC_ERROR_NONE;
@ -577,8 +575,6 @@ class ExternalConnectionHandler : public grpc_core::TcpServerFdHandler {
void Handle(int listener_fd, int fd, grpc_byte_buffer* buf) override {
grpc_pollset* read_notifier_pollset;
grpc_resolved_address addr;
char* addr_str;
char* name;
memset(&addr, 0, sizeof(addr));
addr.len = static_cast<socklen_t>(sizeof(struct sockaddr_storage));
grpc_core::ExecCtx exec_ctx;
@ -590,13 +586,13 @@ class ExternalConnectionHandler : public grpc_core::TcpServerFdHandler {
return;
}
grpc_set_socket_no_sigpipe_if_possible(fd);
addr_str = grpc_sockaddr_to_uri(&addr);
gpr_asprintf(&name, "tcp-server-connection:%s", addr_str);
std::string addr_str = grpc_sockaddr_to_uri(&addr);
if (grpc_tcp_trace.enabled()) {
gpr_log(GPR_INFO, "SERVER_CONNECT: incoming external connection: %s",
addr_str);
addr_str.c_str());
}
grpc_fd* fdobj = grpc_fd_create(fd, name, true);
std::string name = absl::StrCat("tcp-server-connection:", addr_str);
grpc_fd* fdobj = grpc_fd_create(fd, name.c_str(), true);
read_notifier_pollset =
s_->pollsets[static_cast<size_t>(gpr_atm_no_barrier_fetch_add(
&s_->next_pollset_to_assign, 1)) %
@ -611,10 +607,8 @@ class ExternalConnectionHandler : public grpc_core::TcpServerFdHandler {
acceptor->listener_fd = listener_fd;
acceptor->pending_data = buf;
s_->on_accept_cb(s_->on_accept_cb_arg,
grpc_tcp_create(fdobj, s_->channel_args, addr_str),
grpc_tcp_create(fdobj, s_->channel_args, addr_str.c_str()),
read_notifier_pollset, acceptor);
gpr_free(name);
gpr_free(addr_str);
}
private:

@ -31,9 +31,10 @@
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/sync.h>
#include "src/core/lib/iomgr/error.h"
@ -85,15 +86,13 @@ static grpc_error* add_socket_to_server(grpc_tcp_server* s, int fd,
grpc_tcp_listener** listener) {
grpc_tcp_listener* sp = nullptr;
int port = -1;
std::string addr_str;
char* name;
grpc_error* err =
grpc_tcp_server_prepare_socket(s, fd, addr, s->so_reuseport, &port);
if (err == GRPC_ERROR_NONE) {
GPR_ASSERT(port > 0);
addr_str = grpc_sockaddr_to_string(addr, true);
gpr_asprintf(&name, "tcp-server-listener:%s", addr_str.c_str());
std::string addr_str = grpc_sockaddr_to_string(addr, true);
std::string name = absl::StrCat("tcp-server-listener:", addr_str);
gpr_mu_lock(&s->mu);
s->nports++;
GPR_ASSERT(!s->on_accept_cb && "must add ports before starting server");
@ -107,7 +106,7 @@ static grpc_error* add_socket_to_server(grpc_tcp_server* s, int fd,
s->tail = sp;
sp->server = s;
sp->fd = fd;
sp->emfd = grpc_fd_create(fd, name, true);
sp->emfd = grpc_fd_create(fd, name.c_str(), true);
memcpy(&sp->addr, addr, sizeof(grpc_resolved_address));
sp->port = port;
sp->port_index = port_index;
@ -116,7 +115,6 @@ static grpc_error* add_socket_to_server(grpc_tcp_server* s, int fd,
sp->sibling = nullptr;
GPR_ASSERT(sp->emfd);
gpr_mu_unlock(&s->mu);
gpr_free(name);
}
*listener = sp;

@ -31,9 +31,10 @@
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/iomgr/sockaddr.h"
@ -145,14 +146,8 @@ grpc_error* grpc_tcp_server_add_all_local_addrs(grpc_tcp_server* s,
}
if ((err = grpc_tcp_server_add_addr(s, &addr, port_index, fd_index, &dsmode,
&new_sp)) != GRPC_ERROR_NONE) {
char* err_str = nullptr;
grpc_error* root_err;
if (gpr_asprintf(&err_str, "Failed to add listener: %s",
addr_str.c_str()) < 0) {
err_str = gpr_strdup("Failed to add listener");
}
root_err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(err_str);
gpr_free(err_str);
grpc_error* root_err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Failed to add listener: ", addr_str).c_str());
err = grpc_error_add_child(root_err, err);
break;
} else {

@ -27,6 +27,8 @@
#include <inttypes.h>
#include <io.h>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/log_windows.h>
@ -42,6 +44,7 @@
#include "src/core/lib/iomgr/socket_windows.h"
#include "src/core/lib/iomgr/tcp_server.h"
#include "src/core/lib/iomgr/tcp_windows.h"
#include "src/core/lib/slice/slice_internal.h"
#define MIN_SAFE_ACCEPT_QUEUE_SIZE 100
@ -222,14 +225,13 @@ static grpc_error* prepare_socket(SOCKET sock,
failure:
GPR_ASSERT(error != GRPC_ERROR_NONE);
char* tgtaddr = grpc_sockaddr_to_uri(addr);
grpc_error_set_int(
grpc_error_set_str(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Failed to prepare server socket", &error, 1),
GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_copied_string(tgtaddr)),
grpc_error_set_str(
GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Failed to prepare server socket", &error, 1),
GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_cpp_string(grpc_sockaddr_to_uri(addr))),
GRPC_ERROR_INT_FD, (intptr_t)sock);
gpr_free(tgtaddr);
GRPC_ERROR_UNREF(error);
if (sock != INVALID_SOCKET) closesocket(sock);
return error;
@ -301,8 +303,6 @@ static void on_accept(void* arg, grpc_error* error) {
grpc_winsocket_callback_info* info = &sp->socket->read_info;
grpc_endpoint* ep = NULL;
grpc_resolved_address peer_name;
char* peer_name_string;
char* fd_name;
DWORD transfered_bytes;
DWORD flags;
BOOL wsa_success;
@ -337,7 +337,6 @@ static void on_accept(void* arg, grpc_error* error) {
closesocket(sock);
} else {
if (!sp->shutting_down) {
peer_name_string = NULL;
err = setsockopt(sock, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
(char*)&sp->socket->socket, sizeof(sp->socket->socket));
if (err) {
@ -348,6 +347,7 @@ static void on_accept(void* arg, grpc_error* error) {
int peer_name_len = (int)peer_name.len;
err = getpeername(sock, (grpc_sockaddr*)peer_name.addr, &peer_name_len);
peer_name.len = (size_t)peer_name_len;
std::string peer_name_string;
if (!err) {
peer_name_string = grpc_sockaddr_to_uri(&peer_name);
} else {
@ -355,11 +355,9 @@ static void on_accept(void* arg, grpc_error* error) {
gpr_log(GPR_ERROR, "getpeername error: %s", utf8_message);
gpr_free(utf8_message);
}
gpr_asprintf(&fd_name, "tcp_server:%s", peer_name_string);
ep = grpc_tcp_create(grpc_winsocket_create(sock, fd_name),
sp->server->channel_args, peer_name_string);
gpr_free(fd_name);
gpr_free(peer_name_string);
std::string fd_name = absl::StrCat("tcp_server:", peer_name_string);
ep = grpc_tcp_create(grpc_winsocket_create(sock, fd_name.c_str()),
sp->server->channel_args, peer_name_string.c_str());
} else {
closesocket(sock);
}

@ -22,12 +22,15 @@
#include <inttypes.h>
#include <string>
#include "absl/strings/str_cat.h"
#include "src/core/lib/iomgr/timer.h"
#include <grpc/support/alloc.h>
#include <grpc/support/cpu.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/sync.h>
#include "src/core/lib/debug/trace.h"
@ -706,38 +709,36 @@ static grpc_timer_check_result timer_check(grpc_millis* next) {
// tracing
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
char* next_str;
std::string next_str;
if (next == nullptr) {
next_str = gpr_strdup("NULL");
next_str = "NULL";
} else {
gpr_asprintf(&next_str, "%" PRId64, *next);
next_str = absl::StrCat(*next);
}
#if GPR_ARCH_64
gpr_log(GPR_INFO,
"TIMER CHECK BEGIN: now=%" PRId64 " next=%s tls_min=%" PRId64
" glob_min=%" PRId64,
now, next_str, min_timer,
now, next_str.c_str(), min_timer,
static_cast<grpc_millis>(gpr_atm_no_barrier_load(
(gpr_atm*)(&g_shared_mutables.min_timer))));
#else
gpr_log(GPR_INFO, "TIMER CHECK BEGIN: now=%" PRId64 " next=%s min=%" PRId64,
now, next_str, min_timer);
now, next_str.c_str(), min_timer);
#endif
gpr_free(next_str);
}
// actual code
grpc_timer_check_result r =
run_some_expired_timers(now, next, shutdown_error);
// tracing
if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) {
char* next_str;
std::string next_str;
if (next == nullptr) {
next_str = gpr_strdup("NULL");
next_str = "NULL";
} else {
gpr_asprintf(&next_str, "%" PRId64, *next);
next_str = absl::StrCat(*next);
}
gpr_log(GPR_INFO, "TIMER CHECK END: r=%d; next=%s", r, next_str);
gpr_free(next_str);
gpr_log(GPR_INFO, "TIMER CHECK END: r=%d; next=%s", r, next_str.c_str());
}
return r;
}

@ -44,7 +44,10 @@
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include "absl/container/inlined_vector.h"
#include "absl/strings/str_cat.h"
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
@ -148,13 +151,11 @@ GrpcUdpListener::GrpcUdpListener(grpc_udp_server* server, int fd,
server_(server),
orphan_notified_(false),
already_shutdown_(false) {
char* name;
std::string addr_str = grpc_sockaddr_to_string(addr, true);
gpr_asprintf(&name, "udp-server-listener:%s", addr_str.c_str());
emfd_ = grpc_fd_create(fd, name, true);
std::string name = absl::StrCat("udp-server-listener:", addr_str);
emfd_ = grpc_fd_create(fd, name.c_str(), true);
memcpy(&addr_, addr, sizeof(grpc_resolved_address));
GPR_ASSERT(emfd_);
gpr_free(name);
gpr_mu_init(&mutex_);
}

@ -28,6 +28,8 @@
#include <sys/types.h>
#include <sys/un.h>
#include "absl/strings/str_cat.h"
#include "src/core/lib/iomgr/unix_sockets_posix.h"
#include <grpc/support/alloc.h>
@ -44,14 +46,10 @@ grpc_error* grpc_resolve_unix_domain_address(const char* name,
struct sockaddr_un* un;
if (strlen(name) >
GPR_ARRAY_SIZE(((struct sockaddr_un*)nullptr)->sun_path) - 1) {
char* err_msg;
grpc_error* err;
gpr_asprintf(&err_msg,
"Path name should not have more than %" PRIuPTR " characters.",
GPR_ARRAY_SIZE(un->sun_path) - 1);
err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(err_msg);
gpr_free(err_msg);
return err;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Path name should not have more than ",
GPR_ARRAY_SIZE(un->sun_path) - 1, " characters")
.c_str());
}
*addrs = static_cast<grpc_resolved_addresses*>(
gpr_malloc(sizeof(grpc_resolved_addresses)));
@ -88,17 +86,14 @@ void grpc_unlink_if_unix_domain_socket(
}
}
char* grpc_sockaddr_to_uri_unix_if_possible(
std::string grpc_sockaddr_to_uri_unix_if_possible(
const grpc_resolved_address* resolved_addr) {
const grpc_sockaddr* addr =
reinterpret_cast<const grpc_sockaddr*>(resolved_addr->addr);
if (addr->sa_family != AF_UNIX) {
return nullptr;
return "";
}
char* result;
gpr_asprintf(&result, "unix:%s", ((struct sockaddr_un*)addr)->sun_path);
return result;
return absl::StrCat("unix:", ((struct sockaddr_un*)addr)->sun_path);
}
#endif

@ -21,6 +21,8 @@
#include <grpc/support/port_platform.h>
#include <string>
#include "src/core/lib/iomgr/port.h"
#include <grpc/support/string_util.h>
@ -37,7 +39,7 @@ int grpc_is_unix_socket(const grpc_resolved_address* resolved_addr);
void grpc_unlink_if_unix_domain_socket(
const grpc_resolved_address* resolved_addr);
char* grpc_sockaddr_to_uri_unix_if_possible(
std::string grpc_sockaddr_to_uri_unix_if_possible(
const grpc_resolved_address* resolved_addr);
#endif /* GRPC_CORE_LIB_IOMGR_UNIX_SOCKETS_POSIX_H */

@ -22,6 +22,8 @@
#ifndef GRPC_HAVE_UNIX_SOCKET
#include <string>
#include <grpc/support/log.h>
void grpc_create_socketpair_if_unix(int sv[2]) {
@ -42,8 +44,9 @@ int grpc_is_unix_socket(const grpc_resolved_address* addr) { return false; }
void grpc_unlink_if_unix_domain_socket(const grpc_resolved_address* addr) {}
char* grpc_sockaddr_to_uri_unix_if_possible(const grpc_resolved_address* addr) {
return NULL;
std::string grpc_sockaddr_to_uri_unix_if_possible(
const grpc_resolved_address* addr) {
return "";
}
#endif

@ -20,8 +20,12 @@
#include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/json/json.h"
@ -176,11 +180,10 @@ Json* JsonReader::CreateAndLinkValue() {
if (errors_.size() == GRPC_JSON_MAX_ERRORS) {
truncated_errors_ = true;
} else {
char* msg;
gpr_asprintf(&msg, "duplicate key \"%s\" at index %" PRIuPTR,
key_.c_str(), CurrentIndex());
errors_.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg));
gpr_free(msg);
errors_.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("duplicate key \"%s\" at index %" PRIuPTR, key_,
CurrentIndex())
.c_str()));
}
}
value = &(*parent->mutable_object())[std::move(key_)];
@ -198,11 +201,10 @@ bool JsonReader::StartContainer(Json::Type type) {
if (errors_.size() == GRPC_JSON_MAX_ERRORS) {
truncated_errors_ = true;
} else {
char* msg;
gpr_asprintf(&msg, "exceeded max stack depth (%d) at index %" PRIuPTR,
GRPC_JSON_MAX_DEPTH, CurrentIndex());
errors_.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg));
gpr_free(msg);
errors_.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("exceeded max stack depth (%d) at index %" PRIuPTR,
GRPC_JSON_MAX_DEPTH, CurrentIndex())
.c_str()));
}
return false;
}
@ -824,17 +826,14 @@ grpc_error* JsonReader::Parse(absl::string_view input, Json* output) {
"errors and try again to see additional errors"));
}
if (status == Status::GRPC_JSON_INTERNAL_ERROR) {
char* msg;
gpr_asprintf(&msg, "internal error in JSON parser at index %" PRIuPTR,
reader.CurrentIndex());
reader.errors_.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg));
gpr_free(msg);
reader.errors_.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("internal error in JSON parser at index ",
reader.CurrentIndex())
.c_str()));
} else if (status == Status::GRPC_JSON_PARSE_ERROR) {
char* msg;
gpr_asprintf(&msg, "JSON parse error at index %" PRIuPTR,
reader.CurrentIndex());
reader.errors_.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg));
gpr_free(msg);
reader.errors_.push_back(GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("JSON parse error at index ", reader.CurrentIndex())
.c_str()));
}
if (!reader.errors_.empty()) {
return GRPC_ERROR_CREATE_FROM_VECTOR("JSON parsing failed",

@ -23,6 +23,8 @@
#include <string.h>
#include <string>
#include <grpc/grpc.h>
#include <grpc/grpc_security.h>
#include <grpc/support/sync.h>
@ -79,13 +81,13 @@ typedef enum {
/* --- Google utils --- */
/* It is the caller's responsibility to gpr_free the result if not NULL. */
char* grpc_get_well_known_google_credentials_file_path(void);
std::string grpc_get_well_known_google_credentials_file_path(void);
/* Implementation function for the different platforms. */
char* grpc_get_well_known_google_credentials_file_path_impl(void);
std::string grpc_get_well_known_google_credentials_file_path_impl(void);
/* Override for testing only. Not thread-safe */
typedef char* (*grpc_well_known_credentials_path_getter)(void);
typedef std::string (*grpc_well_known_credentials_path_getter)(void);
void grpc_override_well_known_credentials_path_getter(
grpc_well_known_credentials_path_getter getter);

@ -20,22 +20,24 @@
#include "src/core/lib/security/credentials/google_default/google_default_credentials.h"
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/env.h"
#include "src/core/lib/gpr/string.h"
char* grpc_get_well_known_google_credentials_file_path_impl(void) {
char* result = nullptr;
std::string grpc_get_well_known_google_credentials_file_path_impl(void) {
char* base = gpr_getenv(GRPC_GOOGLE_CREDENTIALS_PATH_ENV_VAR);
if (base == nullptr) {
gpr_log(GPR_ERROR, "Could not get " GRPC_GOOGLE_CREDENTIALS_PATH_ENV_VAR
" environment variable.");
return nullptr;
return "";
}
gpr_asprintf(&result, "%s/%s", base, GRPC_GOOGLE_CREDENTIALS_PATH_SUFFIX);
std::string result =
absl::StrCat(base, "/", GRPC_GOOGLE_CREDENTIALS_PATH_SUFFIX);
gpr_free(base);
return result;
}

@ -216,18 +216,19 @@ static int is_metadata_server_reachable() {
/* Takes ownership of creds_path if not NULL. */
static grpc_error* create_default_creds_from_path(
char* creds_path, grpc_core::RefCountedPtr<grpc_call_credentials>* creds) {
const std::string& creds_path,
grpc_core::RefCountedPtr<grpc_call_credentials>* creds) {
grpc_auth_json_key key;
grpc_auth_refresh_token token;
grpc_core::RefCountedPtr<grpc_call_credentials> result;
grpc_slice creds_data = grpc_empty_slice();
grpc_error* error = GRPC_ERROR_NONE;
Json json;
if (creds_path == nullptr) {
if (creds_path.empty()) {
error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("creds_path unset");
goto end;
}
error = grpc_load_file(creds_path, 0, &creds_data);
error = grpc_load_file(creds_path.c_str(), 0, &creds_data);
if (error != GRPC_ERROR_NONE) goto end;
json = Json::Parse(grpc_core::StringViewFromSlice(creds_data), &error);
if (error != GRPC_ERROR_NONE) goto end;
@ -267,7 +268,6 @@ static grpc_error* create_default_creds_from_path(
end:
GPR_ASSERT((result == nullptr) + (error == GRPC_ERROR_NONE) == 1);
if (creds_path != nullptr) gpr_free(creds_path);
grpc_slice_unref_internal(creds_data);
*creds = result;
return error;
@ -286,10 +286,13 @@ grpc_channel_credentials* grpc_google_default_credentials_create() {
gpr_once_init(&g_once, init_default_credentials);
/* First, try the environment variable. */
err = create_default_creds_from_path(
gpr_getenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR), &call_creds);
if (err == GRPC_ERROR_NONE) goto end;
error = grpc_error_add_child(error, err);
char* path_from_env = gpr_getenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR);
if (path_from_env != nullptr) {
err = create_default_creds_from_path(path_from_env, &call_creds);
gpr_free(path_from_env);
if (err == GRPC_ERROR_NONE) goto end;
error = grpc_error_add_child(error, err);
}
/* Then the well-known file. */
err = create_default_creds_from_path(
@ -372,7 +375,7 @@ void grpc_flush_cached_google_default_credentials(void) {
static grpc_well_known_credentials_path_getter creds_path_getter = nullptr;
char* grpc_get_well_known_google_credentials_file_path(void) {
std::string grpc_get_well_known_google_credentials_file_path(void) {
if (creds_path_getter != nullptr) return creds_path_getter();
return grpc_get_well_known_google_credentials_file_path_impl();
}

@ -23,8 +23,13 @@
#include <inttypes.h>
#include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/surface/api_trace.h"
#include <grpc/support/alloc.h>
@ -81,16 +86,14 @@ bool grpc_service_account_jwt_access_credentials::get_request_metadata(
jwt = grpc_jwt_encode_and_sign(&key_, context.service_url, jwt_lifetime_,
nullptr);
if (jwt != nullptr) {
char* md_value;
gpr_asprintf(&md_value, "Bearer %s", jwt);
std::string md_value = absl::StrCat("Bearer ", jwt);
gpr_free(jwt);
cached_.jwt_expiration =
gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), jwt_lifetime_);
cached_.service_url = gpr_strdup(context.service_url);
cached_.jwt_md = grpc_mdelem_from_slices(
grpc_slice_from_static_string(GRPC_AUTHORIZATION_METADATA_KEY),
grpc_slice_from_copied_string(md_value));
gpr_free(md_value);
grpc_slice_from_cpp_string(std::move(md_value)));
jwt_md = GRPC_MDELEM_REF(cached_.jwt_md);
}
gpr_mu_unlock(&cache_mu_);

@ -24,6 +24,8 @@
#include <string.h>
#include "absl/container/inlined_vector.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"
#include <grpc/grpc_security.h>
@ -33,7 +35,6 @@
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "absl/strings/str_format.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/error.h"
@ -136,7 +137,6 @@ grpc_oauth2_token_fetcher_credentials_parse_server_response(
const grpc_http_response* response, grpc_mdelem* token_md,
grpc_millis* token_lifetime) {
char* null_terminated_body = nullptr;
char* new_access_token = nullptr;
grpc_credentials_status status = GRPC_CREDENTIALS_OK;
Json json;
@ -202,12 +202,12 @@ grpc_oauth2_token_fetcher_credentials_parse_server_response(
goto end;
}
expires_in = it->second.string_value().c_str();
gpr_asprintf(&new_access_token, "%s %s", token_type, access_token);
*token_lifetime = strtol(expires_in, nullptr, 10) * GPR_MS_PER_SEC;
if (!GRPC_MDISNULL(*token_md)) GRPC_MDELEM_UNREF(*token_md);
*token_md = grpc_mdelem_from_slices(
grpc_core::ExternallyManagedSlice(GRPC_AUTHORIZATION_METADATA_KEY),
grpc_core::UnmanagedMemorySlice(new_access_token));
grpc_slice_from_cpp_string(
absl::StrCat(token_type, " ", access_token)));
status = GRPC_CREDENTIALS_OK;
}
@ -216,8 +216,7 @@ end:
GRPC_MDELEM_UNREF(*token_md);
*token_md = GRPC_MDNULL;
}
if (null_terminated_body != nullptr) gpr_free(null_terminated_body);
if (new_access_token != nullptr) gpr_free(new_access_token);
gpr_free(null_terminated_body);
return status;
}
@ -442,10 +441,9 @@ void grpc_google_refresh_token_credentials::fetch_oauth2(
const_cast<char*>("Content-Type"),
const_cast<char*>("application/x-www-form-urlencoded")};
grpc_httpcli_request request;
char* body = nullptr;
gpr_asprintf(&body, GRPC_REFRESH_TOKEN_POST_BODY_FORMAT_STRING,
refresh_token_.client_id, refresh_token_.client_secret,
refresh_token_.refresh_token);
std::string body = absl::StrFormat(
GRPC_REFRESH_TOKEN_POST_BODY_FORMAT_STRING, refresh_token_.client_id,
refresh_token_.client_secret, refresh_token_.refresh_token);
memset(&request, 0, sizeof(grpc_httpcli_request));
request.host = (char*)GRPC_GOOGLE_OAUTH2_SERVICE_HOST;
request.http.path = (char*)GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH;
@ -457,13 +455,12 @@ void grpc_google_refresh_token_credentials::fetch_oauth2(
extreme memory pressure. */
grpc_resource_quota* resource_quota =
grpc_resource_quota_create("oauth2_credentials_refresh");
grpc_httpcli_post(httpcli_context, pollent, resource_quota, &request, body,
strlen(body), deadline,
grpc_httpcli_post(httpcli_context, pollent, resource_quota, &request,
body.c_str(), body.size(), deadline,
GRPC_CLOSURE_INIT(&http_post_cb_closure_, response_cb,
metadata_req, grpc_schedule_on_exec_ctx),
&metadata_req->response);
grpc_resource_quota_unref_internal(resource_quota);
gpr_free(body);
}
grpc_google_refresh_token_credentials::grpc_google_refresh_token_credentials(
@ -487,16 +484,15 @@ std::string grpc_google_refresh_token_credentials::debug_string() {
grpc_oauth2_token_fetcher_credentials::debug_string());
}
static char* create_loggable_refresh_token(grpc_auth_refresh_token* token) {
static std::string create_loggable_refresh_token(
grpc_auth_refresh_token* token) {
if (strcmp(token->type, GRPC_AUTH_JSON_TYPE_INVALID) == 0) {
return gpr_strdup("<Invalid json token>");
return "<Invalid json token>";
}
char* loggable_token = nullptr;
gpr_asprintf(&loggable_token,
"{\n type: %s\n client_id: %s\n client_secret: "
"<redacted>\n refresh_token: <redacted>\n}",
token->type, token->client_id);
return loggable_token;
return absl::StrFormat(
"{\n type: %s\n client_id: %s\n client_secret: "
"<redacted>\n refresh_token: <redacted>\n}",
token->type, token->client_id);
}
grpc_call_credentials* grpc_google_refresh_token_credentials_create(
@ -504,12 +500,10 @@ grpc_call_credentials* grpc_google_refresh_token_credentials_create(
grpc_auth_refresh_token token =
grpc_auth_refresh_token_create_from_string(json_refresh_token);
if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace)) {
char* loggable_token = create_loggable_refresh_token(&token);
gpr_log(GPR_INFO,
"grpc_refresh_token_credentials_create(json_refresh_token=%s, "
"reserved=%p)",
loggable_token, reserved);
gpr_free(loggable_token);
create_loggable_refresh_token(&token).c_str(), reserved);
}
GPR_ASSERT(reserved == nullptr);
return grpc_refresh_token_credentials_create_from_auth_refresh_token(token)
@ -744,13 +738,10 @@ void grpc_access_token_credentials::cancel_get_request_metadata(
grpc_access_token_credentials::grpc_access_token_credentials(
const char* access_token)
: grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) {
char* token_md_value;
gpr_asprintf(&token_md_value, "Bearer %s", access_token);
grpc_core::ExecCtx exec_ctx;
access_token_md_ = grpc_mdelem_from_slices(
grpc_core::ExternallyManagedSlice(GRPC_AUTHORIZATION_METADATA_KEY),
grpc_core::UnmanagedMemorySlice(token_md_value));
gpr_free(token_md_value);
grpc_slice_from_cpp_string(absl::StrCat("Bearer ", access_token)));
}
std::string grpc_access_token_credentials::debug_string() {

@ -22,10 +22,11 @@
#include <string.h>
#include "absl/strings/str_cat.h"
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/sync.h>
#include "src/core/lib/slice/slice_internal.h"
@ -86,11 +87,10 @@ static grpc_error* process_plugin_result(
size_t num_md, grpc_status_code status, const char* error_details) {
grpc_error* error = GRPC_ERROR_NONE;
if (status != GRPC_STATUS_OK) {
char* msg;
gpr_asprintf(&msg, "Getting metadata from plugin failed with error: %s",
error_details);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Getting metadata from plugin failed with error: ",
error_details)
.c_str());
} else {
bool seen_illegal_header = false;
for (size_t i = 0; i < num_md; ++i) {

@ -22,6 +22,8 @@
#include <stdbool.h>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
@ -227,11 +229,10 @@ static void fake_check_peer(
prop_name = peer.properties[0].name;
if (prop_name == nullptr ||
strcmp(prop_name, TSI_CERTIFICATE_TYPE_PEER_PROPERTY)) {
char* msg;
gpr_asprintf(&msg, "Unexpected property in fake peer: %s.",
prop_name == nullptr ? "<EMPTY>" : prop_name);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Unexpected property in fake peer: ",
prop_name == nullptr ? "<EMPTY>" : prop_name)
.c_str());
goto end;
}
if (strncmp(peer.properties[0].value.data, TSI_FAKE_CERTIFICATE_TYPE,
@ -243,11 +244,10 @@ static void fake_check_peer(
prop_name = peer.properties[1].name;
if (prop_name == nullptr ||
strcmp(prop_name, TSI_SECURITY_LEVEL_PEER_PROPERTY) != 0) {
char* msg;
gpr_asprintf(&msg, "Unexpected property in fake peer: %s.",
prop_name == nullptr ? "<EMPTY>" : prop_name);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Unexpected property in fake peer: ",
prop_name == nullptr ? "<EMPTY>" : prop_name)
.c_str());
goto end;
}
if (strncmp(peer.properties[1].value.data, TSI_FAKE_SECURITY_LEVEL,

@ -22,11 +22,12 @@
#include <stdbool.h>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/transport/chttp2/alpn/alpn.h"
#include "src/core/lib/channel/handshaker.h"
@ -53,11 +54,9 @@ grpc_error* ssl_check_peer(
}
/* Check the peer name if specified. */
if (peer_name != nullptr && !grpc_ssl_host_matches_name(peer, peer_name)) {
char* msg;
gpr_asprintf(&msg, "Peer name %s is not in peer certificate", peer_name);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return error;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Peer name ", peer_name, " is not in peer certificate")
.c_str());
}
*auth_context =
grpc_ssl_peer_to_auth_context(peer, GRPC_SSL_TRANSPORT_SECURITY_TYPE);
@ -163,11 +162,10 @@ class grpc_ssl_channel_security_connector final
verify_options_->verify_peer_callback_userdata);
gpr_free(peer_pem);
if (callback_status) {
char* msg;
gpr_asprintf(&msg, "Verify peer callback returned a failure (%d)",
callback_status);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrFormat("Verify peer callback returned a failure (%d)",
callback_status)
.c_str());
}
}
}

@ -20,12 +20,13 @@
#include "src/core/lib/security/security_connector/ssl_utils.h"
#include <vector>
#include "absl/strings/str_cat.h"
#include <grpc/slice_buffer.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <vector>
#include "src/core/ext/transport/chttp2/alpn/alpn.h"
#include "src/core/lib/channel/channel_args.h"
@ -170,12 +171,9 @@ grpc_error* grpc_ssl_check_peer_name(absl::string_view peer_name,
const tsi_peer* peer) {
/* Check the peer name if specified. */
if (!peer_name.empty() && !grpc_ssl_host_matches_name(peer, peer_name)) {
char* msg;
gpr_asprintf(&msg, "Peer name %s is not in peer certificate",
peer_name.data());
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return error;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Peer name ", peer_name, " is not in peer certificate")
.c_str());
}
return GRPC_ERROR_NONE;
}

@ -23,6 +23,7 @@
#include <stdbool.h>
#include <string.h>
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include <grpc/grpc.h>
@ -130,11 +131,9 @@ grpc_status_code TlsFetchKeyMaterials(
grpc_error* TlsCheckHostName(const char* peer_name, const tsi_peer* peer) {
/* Check the peer name if specified. */
if (peer_name != nullptr && !grpc_ssl_host_matches_name(peer, peer_name)) {
char* msg;
gpr_asprintf(&msg, "Peer name %s is not in peer certificate", peer_name);
grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return error;
return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Peer name ", peer_name, " is not in peer certificate")
.c_str());
}
return GRPC_ERROR_NONE;
}
@ -402,31 +401,30 @@ void TlsChannelSecurityConnector::ServerAuthorizationCheckDone(
grpc_error* TlsChannelSecurityConnector::ProcessServerAuthorizationCheckResult(
grpc_tls_server_authorization_check_arg* arg) {
grpc_error* error = GRPC_ERROR_NONE;
char* msg = nullptr;
/* Server authorization check is cancelled by caller. */
if (arg->status == GRPC_STATUS_CANCELLED) {
gpr_asprintf(&msg,
"Server authorization check is cancelled by the caller with "
"error: %s",
arg->error_details->error_details().c_str());
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Server authorization check is cancelled by the caller "
"with error: ",
arg->error_details->error_details())
.c_str());
} else if (arg->status == GRPC_STATUS_OK) {
/* Server authorization check completed successfully but returned check
* failure. */
if (!arg->success) {
gpr_asprintf(&msg, "Server authorization check failed with error: %s",
arg->error_details->error_details().c_str());
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Server authorization check failed with error: ",
arg->error_details->error_details())
.c_str());
}
/* Server authorization check did not complete correctly. */
} else {
gpr_asprintf(
&msg,
"Server authorization check did not finish correctly with error: %s",
arg->error_details->error_details().c_str());
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat(
"Server authorization check did not finish correctly with error: ",
arg->error_details->error_details())
.c_str());
}
gpr_free(msg);
return error;
}

@ -22,6 +22,10 @@
#include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
@ -331,18 +335,15 @@ static void on_host_checked(void* arg, grpc_error* error) {
if (error == GRPC_ERROR_NONE) {
send_security_metadata(elem, batch);
} else {
char* error_msg;
char* host = grpc_slice_to_c_string(calld->host);
gpr_asprintf(&error_msg, "Invalid host %s set in :authority metadata.",
host);
gpr_free(host);
std::string error_msg = absl::StrCat(
"Invalid host ", grpc_core::StringViewFromSlice(calld->host),
" set in :authority metadata.");
grpc_transport_stream_op_batch_finish_with_failure(
batch,
grpc_error_set_int(GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg),
GRPC_ERROR_INT_GRPC_STATUS,
GRPC_STATUS_UNAUTHENTICATED),
grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg.c_str()),
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAUTHENTICATED),
calld->call_combiner);
gpr_free(error_msg);
}
GRPC_CALL_STACK_UNREF(calld->owning_call, "check_call_host");
}

@ -18,14 +18,16 @@
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/security/util/json_util.h"
#include <string.h>
#include "absl/strings/str_cat.h"
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/security/util/json_util.h"
const char* grpc_json_get_string_property(const grpc_core::Json& json,
const char* prop_name,
grpc_error** error) {
@ -39,21 +41,18 @@ const char* grpc_json_get_string_property(const grpc_core::Json& json,
auto it = json.object_value().find(prop_name);
if (it == json.object_value().end()) {
if (error != nullptr) {
char* error_msg;
gpr_asprintf(&error_msg, "Property %s not found in JSON object.",
prop_name);
*error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg);
gpr_free(error_msg);
*error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Property ", prop_name, " not found in JSON object.")
.c_str());
}
return nullptr;
}
if (it->second.type() != grpc_core::Json::Type::STRING) {
if (error != nullptr) {
char* error_msg;
gpr_asprintf(&error_msg, "Property %s in JSON object is not a string.",
prop_name);
*error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg);
gpr_free(error_msg);
*error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Property ", prop_name,
" n JSON object is not a string.")
.c_str());
}
return nullptr;
}

@ -156,7 +156,7 @@ class NewWithLenSliceRefcount {
/** grpc_slice_from_moved_(string|buffer) ref count .*/
class MovedStringSliceRefCount {
public:
MovedStringSliceRefCount(grpc_core::UniquePtr<char>&& str)
explicit MovedStringSliceRefCount(grpc_core::UniquePtr<char>&& str)
: base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
&base_),
str_(std::move(str)) {}
@ -173,6 +173,26 @@ class MovedStringSliceRefCount {
grpc_core::UniquePtr<char> str_;
};
// grpc_slice_from_cpp_string() ref count.
class MovedCppStringSliceRefCount {
public:
explicit MovedCppStringSliceRefCount(std::string&& str)
: base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
&base_),
str_(std::move(str)) {}
grpc_slice_refcount* base_refcount() { return &base_; }
private:
static void Destroy(void* arg) {
delete static_cast<MovedCppStringSliceRefCount*>(arg);
}
grpc_slice_refcount base_;
grpc_core::RefCount refs_;
std::string str_;
};
} // namespace grpc_core
grpc_slice grpc_slice_new_with_len(void* p, size_t len,
@ -232,6 +252,23 @@ grpc_slice grpc_slice_from_moved_string(grpc_core::UniquePtr<char> p) {
return grpc_slice_from_moved_buffer(std::move(p), len);
}
grpc_slice grpc_slice_from_cpp_string(std::string str) {
grpc_slice slice;
if (str.size() <= sizeof(slice.data.inlined.bytes)) {
slice.refcount = nullptr;
slice.data.inlined.length = str.size();
memcpy(GRPC_SLICE_START_PTR(slice), str.data(), str.size());
} else {
slice.data.refcounted.bytes =
reinterpret_cast<uint8_t*>(const_cast<char*>(str.data()));
slice.data.refcounted.length = str.size();
slice.refcount =
(new grpc_core::MovedCppStringSliceRefCount(std::move(str)))
->base_refcount();
}
return slice;
}
namespace {
class MallocRefCount {

@ -338,6 +338,7 @@ inline uint32_t grpc_slice_hash_internal(const grpc_slice& s) {
grpc_slice grpc_slice_from_moved_buffer(grpc_core::UniquePtr<char> p,
size_t len);
grpc_slice grpc_slice_from_moved_string(grpc_core::UniquePtr<char> p);
grpc_slice grpc_slice_from_cpp_string(std::string str);
// Returns the memory used by this slice, not counting the slice structure
// itself. This means that inlined and slices from static strings will return

@ -24,6 +24,11 @@
#include <stdlib.h>
#include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include <grpc/compression.h>
#include <grpc/grpc.h>
#include <grpc/slice.h>
@ -1051,14 +1056,12 @@ static void recv_trailing_filter(void* args, grpc_metadata_batch* b,
grpc_get_status_code_from_metadata(b->idx.named.grpc_status->md);
grpc_error* error = GRPC_ERROR_NONE;
if (status_code != GRPC_STATUS_OK) {
char* peer_msg = nullptr;
char* peer = grpc_call_get_peer(call);
gpr_asprintf(&peer_msg, "Error received from peer %s", peer);
error = grpc_error_set_int(GRPC_ERROR_CREATE_FROM_COPIED_STRING(peer_msg),
GRPC_ERROR_INT_GRPC_STATUS,
static_cast<intptr_t>(status_code));
error = grpc_error_set_int(
GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("Error received from peer ", peer).c_str()),
GRPC_ERROR_INT_GRPC_STATUS, static_cast<intptr_t>(status_code));
gpr_free(peer);
gpr_free(peer_msg);
}
if (b->idx.named.grpc_message != nullptr) {
error = grpc_error_set_str(
@ -1369,49 +1372,41 @@ static void receiving_stream_ready_in_call_combiner(void* bctlp,
static void GPR_ATTRIBUTE_NOINLINE
handle_both_stream_and_msg_compression_set(grpc_call* call) {
char* error_msg = nullptr;
gpr_asprintf(&error_msg,
"Incoming stream has both stream compression (%d) and message "
"compression (%d).",
call->incoming_stream_compression_algorithm,
call->incoming_message_compression_algorithm);
gpr_log(GPR_ERROR, "%s", error_msg);
cancel_with_status(call, GRPC_STATUS_INTERNAL, error_msg);
gpr_free(error_msg);
std::string error_msg = absl::StrFormat(
"Incoming stream has both stream compression (%d) and message "
"compression (%d).",
call->incoming_stream_compression_algorithm,
call->incoming_message_compression_algorithm);
gpr_log(GPR_ERROR, "%s", error_msg.c_str());
cancel_with_status(call, GRPC_STATUS_INTERNAL, error_msg.c_str());
}
static void GPR_ATTRIBUTE_NOINLINE
handle_error_parsing_compression_algorithm(grpc_call* call) {
char* error_msg = nullptr;
gpr_asprintf(&error_msg,
"Error in incoming message compression (%d) or stream "
"compression (%d).",
call->incoming_stream_compression_algorithm,
call->incoming_message_compression_algorithm);
cancel_with_status(call, GRPC_STATUS_INTERNAL, error_msg);
gpr_free(error_msg);
std::string error_msg = absl::StrFormat(
"Error in incoming message compression (%d) or stream "
"compression (%d).",
call->incoming_stream_compression_algorithm,
call->incoming_message_compression_algorithm);
cancel_with_status(call, GRPC_STATUS_INTERNAL, error_msg.c_str());
}
static void GPR_ATTRIBUTE_NOINLINE handle_invalid_compression(
grpc_call* call, grpc_compression_algorithm compression_algorithm) {
char* error_msg = nullptr;
gpr_asprintf(&error_msg, "Invalid compression algorithm value '%d'.",
compression_algorithm);
gpr_log(GPR_ERROR, "%s", error_msg);
cancel_with_status(call, GRPC_STATUS_UNIMPLEMENTED, error_msg);
gpr_free(error_msg);
std::string error_msg = absl::StrFormat(
"Invalid compression algorithm value '%d'.", compression_algorithm);
gpr_log(GPR_ERROR, "%s", error_msg.c_str());
cancel_with_status(call, GRPC_STATUS_UNIMPLEMENTED, error_msg.c_str());
}
static void GPR_ATTRIBUTE_NOINLINE handle_compression_algorithm_disabled(
grpc_call* call, grpc_compression_algorithm compression_algorithm) {
char* error_msg = nullptr;
const char* algo_name = nullptr;
grpc_compression_algorithm_name(compression_algorithm, &algo_name);
gpr_asprintf(&error_msg, "Compression algorithm '%s' is disabled.",
algo_name);
gpr_log(GPR_ERROR, "%s", error_msg);
cancel_with_status(call, GRPC_STATUS_UNIMPLEMENTED, error_msg);
gpr_free(error_msg);
std::string error_msg =
absl::StrFormat("Compression algorithm '%s' is disabled.", algo_name);
gpr_log(GPR_ERROR, "%s", error_msg.c_str());
cancel_with_status(call, GRPC_STATUS_UNIMPLEMENTED, error_msg.c_str());
}
static void GPR_ATTRIBUTE_NOINLINE handle_compression_algorithm_not_accepted(

@ -22,10 +22,13 @@
#include <string.h>
#include <string>
#include "absl/strings/str_format.h"
#include <grpc/slice_buffer.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/slice/percent_encoding.h"
@ -37,22 +40,12 @@
static grpc_uri* bad_uri(const char* uri_text, size_t pos, const char* section,
bool suppress_errors) {
char* line_prefix;
size_t pfx_len;
if (!suppress_errors) {
gpr_asprintf(&line_prefix, "bad uri.%s: '", section);
pfx_len = strlen(line_prefix) + pos;
gpr_log(GPR_ERROR, "%s%s'", line_prefix, uri_text);
gpr_free(line_prefix);
line_prefix = static_cast<char*>(gpr_malloc(pfx_len + 1));
memset(line_prefix, ' ', pfx_len);
line_prefix[pfx_len] = 0;
gpr_log(GPR_ERROR, "%s^ here", line_prefix);
gpr_free(line_prefix);
std::string line_prefix = absl::StrFormat("bad uri.%s: '", section);
gpr_log(GPR_ERROR, "%s%s'", line_prefix.c_str(), uri_text);
size_t pfx_len = line_prefix.size() + pos;
gpr_log(GPR_ERROR, "%s^ here", std::string(pfx_len, ' ').c_str());
}
return nullptr;
}

@ -26,9 +26,10 @@
#include <sys/un.h>
#endif
#include "absl/strings/str_format.h"
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gprpp/host_port.h"
#include "src/core/lib/gprpp/memory.h"
@ -108,18 +109,17 @@ int main(int argc, char** argv) {
}
}
GPR_ASSERT(strlen(arbitrary_interface_name) > 0);
char* target = nullptr;
gpr_asprintf(&target, "ipv6:[fe80::1234%%%s]:12345",
arbitrary_interface_name);
std::string target =
absl::StrFormat("ipv6:[fe80::1234%%%s]:12345", arbitrary_interface_name);
struct sockaddr_in6 result_from_getaddrinfo =
resolve_with_gettaddrinfo(target);
resolve_with_gettaddrinfo(target.c_str());
// Run the test
gpr_log(GPR_DEBUG,
"Run test_grpc_parse_ipv6_parity_with_getaddrinfo with target: %s",
target);
test_grpc_parse_ipv6_parity_with_getaddrinfo(target, result_from_getaddrinfo);
target.c_str());
test_grpc_parse_ipv6_parity_with_getaddrinfo(target.c_str(),
result_from_getaddrinfo);
// Cleanup
gpr_free(target);
gpr_free(arbitrary_interface_name);
grpc_shutdown();
}

@ -18,9 +18,12 @@
#include <string.h>
#include <string>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/filters/client_channel/parse_address.h"
#include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
@ -85,13 +88,12 @@ static grpc_core::OrphanablePtr<grpc_core::Resolver> build_fake_resolver(
static grpc_core::Resolver::Result create_new_resolver_result() {
static size_t test_counter = 0;
const size_t num_addresses = 2;
char* uri_string;
// Create address list.
grpc_core::Resolver::Result result;
for (size_t i = 0; i < num_addresses; ++i) {
gpr_asprintf(&uri_string, "ipv4:127.0.0.1:100%" PRIuPTR,
test_counter * num_addresses + i);
grpc_uri* uri = grpc_uri_parse(uri_string, true);
std::string uri_string = absl::StrFormat("ipv4:127.0.0.1:100%" PRIuPTR,
test_counter * num_addresses + i);
grpc_uri* uri = grpc_uri_parse(uri_string.c_str(), true);
grpc_resolved_address address;
GPR_ASSERT(grpc_parse_uri(uri, &address));
absl::InlinedVector<grpc_arg, 2> args_to_add;
@ -99,7 +101,6 @@ static grpc_core::Resolver::Result create_new_resolver_result() {
address.addr, address.len,
grpc_channel_args_copy_and_add(nullptr, nullptr, 0));
grpc_uri_destroy(uri);
gpr_free(uri_string);
}
++test_counter;
return result;

@ -66,9 +66,8 @@ static void log_resolved_addrs(const char* label, const char* hostname) {
return;
}
for (size_t i = 0; i < res->naddrs; ++i) {
char* addr_str = grpc_sockaddr_to_uri(&res->addrs[i]);
gpr_log(GPR_INFO, "%s: %s", label, addr_str);
gpr_free(addr_str);
gpr_log(GPR_INFO, "%s: %s", label,
grpc_sockaddr_to_uri(&res->addrs[i]).c_str());
}
grpc_resolved_addresses_destroy(res);
}

@ -20,9 +20,12 @@
#include <string.h>
#include <string>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/sync.h>
#include "src/core/ext/filters/client_channel/client_channel.h"
@ -66,21 +69,19 @@ void chttp2_init_client_fullstack(grpc_end2end_test_fixture* f,
grpc_channel_args* client_args) {
fullstack_fixture_data* ffd =
static_cast<fullstack_fixture_data*>(f->fixture_data);
char* proxy_uri;
/* If testing for proxy auth, add credentials to proxy uri */
const grpc_arg* proxy_auth_arg =
grpc_channel_args_find(client_args, GRPC_ARG_HTTP_PROXY_AUTH_CREDS);
const char* proxy_auth_str = grpc_channel_arg_get_string(proxy_auth_arg);
const char* proxy_auth_str = grpc_channel_args_find_string(
client_args, GRPC_ARG_HTTP_PROXY_AUTH_CREDS);
std::string proxy_uri;
if (proxy_auth_str == nullptr) {
gpr_asprintf(&proxy_uri, "http://%s",
grpc_end2end_http_proxy_get_proxy_name(ffd->proxy));
proxy_uri = absl::StrFormat(
"http://%s", grpc_end2end_http_proxy_get_proxy_name(ffd->proxy));
} else {
gpr_asprintf(&proxy_uri, "http://%s@%s", proxy_auth_str,
grpc_end2end_http_proxy_get_proxy_name(ffd->proxy));
proxy_uri =
absl::StrFormat("http://%s@%s", proxy_auth_str,
grpc_end2end_http_proxy_get_proxy_name(ffd->proxy));
}
gpr_setenv("http_proxy", proxy_uri);
gpr_free(proxy_uri);
gpr_setenv("http_proxy", proxy_uri.c_str());
f->client = grpc_insecure_channel_create(ffd->server_addr.c_str(),
client_args, nullptr);
GPR_ASSERT(f->client);

@ -22,9 +22,12 @@
#include <string.h>
#include <unistd.h>
#include <string>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/sync.h>
#include "src/core/ext/filters/client_channel/client_channel.h"
@ -37,22 +40,20 @@
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
typedef struct fullstack_fixture_data {
char* localaddr;
} fullstack_fixture_data;
struct fullstack_fixture_data {
std::string localaddr;
};
static int unique = 1;
static grpc_end2end_test_fixture chttp2_create_fixture_fullstack(
grpc_channel_args* /*client_args*/, grpc_channel_args* /*server_args*/) {
fullstack_fixture_data* ffd = new fullstack_fixture_data;
ffd->localaddr = absl::StrFormat("unix:/tmp/grpc_fullstack_test.%d.%d",
getpid(), unique++);
grpc_end2end_test_fixture f;
fullstack_fixture_data* ffd = static_cast<fullstack_fixture_data*>(
gpr_malloc(sizeof(fullstack_fixture_data)));
memset(&f, 0, sizeof(f));
gpr_asprintf(&ffd->localaddr, "unix:/tmp/grpc_fullstack_test.%d.%d", getpid(),
unique++);
f.fixture_data = ffd;
f.cq = grpc_completion_queue_create_for_next(nullptr);
f.shutdown_cq = grpc_completion_queue_create_for_pluck(nullptr);
@ -64,8 +65,8 @@ void chttp2_init_client_fullstack(grpc_end2end_test_fixture* f,
grpc_channel_args* client_args) {
fullstack_fixture_data* ffd =
static_cast<fullstack_fixture_data*>(f->fixture_data);
f->client =
grpc_insecure_channel_create(ffd->localaddr, client_args, nullptr);
f->client = grpc_insecure_channel_create(ffd->localaddr.c_str(), client_args,
nullptr);
}
void chttp2_init_server_fullstack(grpc_end2end_test_fixture* f,
@ -77,15 +78,15 @@ void chttp2_init_server_fullstack(grpc_end2end_test_fixture* f,
}
f->server = grpc_server_create(server_args, nullptr);
grpc_server_register_completion_queue(f->server, f->cq, nullptr);
GPR_ASSERT(grpc_server_add_insecure_http2_port(f->server, ffd->localaddr));
GPR_ASSERT(
grpc_server_add_insecure_http2_port(f->server, ffd->localaddr.c_str()));
grpc_server_start(f->server);
}
void chttp2_tear_down_fullstack(grpc_end2end_test_fixture* f) {
fullstack_fixture_data* ffd =
static_cast<fullstack_fixture_data*>(f->fixture_data);
gpr_free(ffd->localaddr);
gpr_free(ffd);
delete ffd;
}
/* All test configurations */

@ -22,12 +22,13 @@
#include <string.h>
#include "absl/strings/str_cat.h"
#include <grpc/grpc.h>
#include <grpc/slice_buffer.h>
#include <grpc/support/alloc.h>
#include <grpc/support/atm.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/sync.h>
#include "src/core/lib/channel/channel_args.h"
@ -492,11 +493,10 @@ static void on_read_request_done_locked(void* arg, grpc_error* error) {
}
// Make sure we got a CONNECT request.
if (strcmp(conn->http_request.method, "CONNECT") != 0) {
char* msg;
gpr_asprintf(&msg, "HTTP proxy got request method %s",
conn->http_request.method);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
absl::StrCat("HTTP proxy got request method ",
conn->http_request.method)
.c_str());
proxy_connection_failed(conn, SETUP_FAILED, "HTTP proxy read request",
GRPC_ERROR_REF(error));
GRPC_ERROR_UNREF(error);

@ -23,11 +23,16 @@
#include "src/core/lib/iomgr/sockaddr.h"
#include "src/core/lib/iomgr/socket_utils.h"
#include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <string.h>
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/lib/iomgr/resolve_address.h"
@ -185,7 +190,7 @@ int main(int argc, char** argv) {
int port1 = grpc_pick_unused_port_or_die();
int port2 = grpc_pick_unused_port_or_die();
char* addr;
std::string addr;
grpc_channel_args client_args;
grpc_arg arg_array[2];
@ -242,10 +247,9 @@ int main(int argc, char** argv) {
/* bring a server up on the first port */
grpc_server* server1 = grpc_server_create(nullptr, nullptr);
gpr_asprintf(&addr, "127.0.0.1:%d", port1);
grpc_server_add_insecure_http2_port(server1, addr);
addr = absl::StrCat("127.0.0.1:", port1);
grpc_server_add_insecure_http2_port(server1, addr.c_str());
grpc_server_register_completion_queue(server1, cq, nullptr);
gpr_free(addr);
grpc_server_start(server1);
/* request a call to the server */
@ -319,10 +323,9 @@ int main(int argc, char** argv) {
/* and bring up second server */
set_resolve_port(port2);
grpc_server* server2 = grpc_server_create(nullptr, nullptr);
gpr_asprintf(&addr, "127.0.0.1:%d", port2);
grpc_server_add_insecure_http2_port(server2, addr);
addr = absl::StrCat("127.0.0.1:", port2);
grpc_server_add_insecure_http2_port(server2, addr.c_str());
grpc_server_register_completion_queue(server2, cq, nullptr);
gpr_free(addr);
grpc_server_start(server2);
/* request a call to the server */

@ -21,12 +21,15 @@
#include <stdio.h>
#include <string.h>
#include <string>
#include "absl/strings/str_format.h"
#include <grpc/byte_buffer.h>
#include <grpc/byte_buffer_reader.h>
#include <grpc/compression.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include "src/core/lib/channel/channel_args.h"
@ -246,12 +249,10 @@ static void request_for_disabled_algorithm(
const char* algo_name = nullptr;
GPR_ASSERT(grpc_compression_algorithm_name(algorithm_to_disable, &algo_name));
char* expected_details = nullptr;
gpr_asprintf(&expected_details, "Compression algorithm '%s' is disabled.",
algo_name);
std::string expected_details =
absl::StrFormat("Compression algorithm '%s' is disabled.", algo_name);
/* and we expect a specific reason for it */
GPR_ASSERT(0 == grpc_slice_str_cmp(details, expected_details));
gpr_free(expected_details);
GPR_ASSERT(0 == grpc_slice_str_cmp(details, expected_details.c_str()));
GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, "/foo"));
grpc_slice_unref(details);

@ -21,11 +21,14 @@
#include <stdio.h>
#include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/byte_buffer.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include "src/core/lib/gpr/string.h"
@ -205,7 +208,6 @@ static void test_invoke_10_simple_requests(grpc_end2end_test_config config,
grpc_end2end_test_fixture f;
grpc_arg client_arg;
grpc_channel_args client_args;
char* name;
client_arg.type = GRPC_ARG_INTEGER;
client_arg.key = const_cast<char*>(GRPC_ARG_HTTP2_INITIAL_SEQUENCE_NUMBER);
@ -214,16 +216,15 @@ static void test_invoke_10_simple_requests(grpc_end2end_test_config config,
client_args.num_args = 1;
client_args.args = &client_arg;
gpr_asprintf(&name, "test_invoke_requests first_seqno=%d",
initial_sequence_number);
f = begin_test(config, name, &client_args, nullptr);
std::string name = absl::StrCat("test_invoke_requests first_seqno=",
initial_sequence_number);
f = begin_test(config, name.c_str(), &client_args, nullptr);
for (i = 0; i < 10; i++) {
simple_request_body(config, f);
gpr_log(GPR_INFO, "Running test: Passed simple request %d", i);
}
end_test(&f);
config.tear_down_data(&f);
gpr_free(name);
}
void high_initial_seqno(grpc_end2end_test_config config) {

@ -21,11 +21,14 @@
#include <stdio.h>
#include <string.h>
#include <string>
#include "absl/strings/str_format.h"
#include <grpc/byte_buffer.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include "src/core/lib/gpr/string.h"
@ -355,7 +358,6 @@ static void test_size(grpc_end2end_test_config config, int encode_size,
grpc_channel_args server_args;
grpc_arg client_arg;
grpc_channel_args client_args;
char* name;
server_arg.type = GRPC_ARG_INTEGER;
server_arg.key = const_cast<char*>(GRPC_ARG_HTTP2_HPACK_TABLE_SIZE_DECODER);
@ -369,15 +371,16 @@ static void test_size(grpc_end2end_test_config config, int encode_size,
client_args.num_args = 1;
client_args.args = &client_arg;
gpr_asprintf(&name, "test_size:e=%d:d=%d", encode_size, decode_size);
f = begin_test(config, name, encode_size != 4096 ? &client_args : nullptr,
std::string name =
absl::StrFormat("test_size:e=%d:d=%d", encode_size, decode_size);
f = begin_test(config, name.c_str(),
encode_size != 4096 ? &client_args : nullptr,
decode_size != 4096 ? &server_args : nullptr);
for (i = 0; i < 4 * GPR_ARRAY_SIZE(hobbits); i++) {
simple_request_body(config, f, i);
}
end_test(&f);
config.tear_down_data(&f);
gpr_free(name);
}
void hpack_size(grpc_end2end_test_config config) {

@ -21,10 +21,13 @@
#include <stdio.h>
#include <string.h>
#include <string>
#include "absl/strings/str_format.h"
#include <grpc/byte_buffer.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include "src/core/lib/gpr/useful.h"
@ -90,10 +93,9 @@ static grpc_slice large_slice(void) {
static void test_invoke_large_request(grpc_end2end_test_config config,
int max_frame_size, int lookahead_bytes) {
char* name;
gpr_asprintf(&name,
"test_invoke_large_request:max_frame_size=%d:lookahead_bytes=%d",
max_frame_size, lookahead_bytes);
std::string name = absl::StrFormat(
"test_invoke_large_request:max_frame_size=%d:lookahead_bytes=%d",
max_frame_size, lookahead_bytes);
grpc_arg args[2];
args[0].type = GRPC_ARG_INTEGER;
@ -105,8 +107,7 @@ static void test_invoke_large_request(grpc_end2end_test_config config,
grpc_channel_args channel_args = {GPR_ARRAY_SIZE(args), args};
grpc_end2end_test_fixture f =
begin_test(config, name, &channel_args, &channel_args);
gpr_free(name);
begin_test(config, name.c_str(), &channel_args, &channel_args);
grpc_slice request_payload_slice = large_slice();
grpc_slice response_payload_slice = large_slice();

@ -21,11 +21,14 @@
#include <stdio.h>
#include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/byte_buffer.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/iomgr/error.h"
@ -38,11 +41,9 @@ static void* tag(intptr_t t) { return (void*)t; }
void gpr_default_log(gpr_log_func_args* args);
static void test_no_log(gpr_log_func_args* args) {
char* message = nullptr;
gpr_asprintf(&message, "Unwanted log: %s", args->message);
args->message = message;
std::string message = absl::StrCat("Unwanted log: ", args->message);
args->message = message.c_str();
gpr_default_log(args);
gpr_free(message);
abort();
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save