Merge pull request #23157 from markdroth/gpr_asprintf

Replace most uses of gpr_asprintf() with absl calls.
pull/23419/head
Mark D. Roth 5 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. 77
      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. 18
      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. 23
      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. 46
      src/core/ext/transport/chttp2/transport/hpack_parser.cc
  33. 26
      src/core/ext/transport/chttp2/transport/hpack_table.cc
  34. 58
      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. 15
      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. 22
      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. 17
      src/core/lib/security/credentials/google_default/google_default_credentials.cc
  76. 11
      src/core/lib/security/credentials/jwt/jwt_credentials.cc
  77. 41
      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. 49
      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. 11
      test/core/client_channel/resolvers/fake_resolver_test.cc
  91. 5
      test/core/end2end/dualstack_socket_test.cc
  92. 23
      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. 11
      test/core/end2end/tests/high_initial_seqno.cc
  98. 13
      test/core/end2end/tests/hpack_size.cc
  99. 11
      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 <string.h>
#include "absl/strings/str_cat.h"
#include <grpc/slice_buffer.h> #include <grpc/slice_buffer.h>
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.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. // Make sure we got a 2xx response.
if (handshaker->http_response_.status < 200 || if (handshaker->http_response_.status < 200 ||
handshaker->http_response_.status >= 300) { handshaker->http_response_.status >= 300) {
char* msg; error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(
gpr_asprintf(&msg, "HTTP proxy returned response code %d", absl::StrCat("HTTP proxy returned response code ",
handshaker->http_response_.status); handshaker->http_response_.status)
error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); .c_str());
gpr_free(msg);
handshaker->HandshakeFailedLocked(error); handshaker->HandshakeFailedLocked(error);
goto done; goto done;
} }

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

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

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

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

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

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

@ -24,6 +24,8 @@
#include <string.h> #include <string.h>
#include <sys/ioctl.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 "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h"
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
@ -41,15 +43,13 @@ namespace grpc_core {
class GrpcPolledFdPosix : public GrpcPolledFd { class GrpcPolledFdPosix : public GrpcPolledFd {
public: public:
GrpcPolledFdPosix(ares_socket_t as, grpc_pollset_set* driver_pollset_set) GrpcPolledFdPosix(ares_socket_t as, grpc_pollset_set* driver_pollset_set)
: as_(as) { : name_(absl::StrCat("c-ares fd: ", (int)as)), as_(as) {
gpr_asprintf(&name_, "c-ares fd: %d", (int)as); fd_ = grpc_fd_create((int)as, name_.c_str(), false);
fd_ = grpc_fd_create((int)as, name_, false);
driver_pollset_set_ = driver_pollset_set; driver_pollset_set_ = driver_pollset_set;
grpc_pollset_set_add_fd(driver_pollset_set_, fd_); grpc_pollset_set_add_fd(driver_pollset_set_, fd_);
} }
~GrpcPolledFdPosix() { ~GrpcPolledFdPosix() {
gpr_free(name_);
grpc_pollset_set_del_fd(driver_pollset_set_, fd_); 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 /* 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 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_; } 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_; ares_socket_t as_;
grpc_fd* fd_; grpc_fd* fd_;
grpc_pollset_set* driver_pollset_set_; grpc_pollset_set* driver_pollset_set_;

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

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

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

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

@ -872,7 +872,7 @@ grpc_arg Subchannel::CreateSubchannelAddressArg(
const grpc_resolved_address* addr) { const grpc_resolved_address* addr) {
return grpc_channel_arg_string_create( return grpc_channel_arg_string_create(
(char*)GRPC_ARG_SUBCHANNEL_ADDRESS, (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( const char* Subchannel::GetUriFromSubchannelAddressArg(

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

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

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

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

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

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

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

@ -21,10 +21,11 @@
#include <limits.h> #include <limits.h>
#include <string.h> #include <string.h>
#include "absl/strings/str_format.h"
#include <grpc/impl/codegen/grpc_types.h> #include <grpc/impl/codegen/grpc_types.h>
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.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.h"
#include "src/core/ext/filters/client_channel/service_config_call_data.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 && if (*calld->recv_message != nullptr && calld->limits.max_recv_size >= 0 &&
(*calld->recv_message)->length() > (*calld->recv_message)->length() >
static_cast<size_t>(calld->limits.max_recv_size)) { 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* 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); GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_RESOURCE_EXHAUSTED);
error = grpc_error_add_child(GRPC_ERROR_REF(error), new_error); error = grpc_error_add_child(GRPC_ERROR_REF(error), new_error);
GRPC_ERROR_UNREF(calld->error); GRPC_ERROR_UNREF(calld->error);
calld->error = GRPC_ERROR_REF(error); calld->error = GRPC_ERROR_REF(error);
gpr_free(message_string);
} else { } else {
GRPC_ERROR_REF(error); 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 && if (op->send_message && calld->limits.max_send_size >= 0 &&
op->payload->send_message.send_message->length() > op->payload->send_message.send_message->length() >
static_cast<size_t>(calld->limits.max_send_size)) { 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( grpc_transport_stream_op_batch_finish_with_failure(
op, op,
grpc_error_set_int(GRPC_ERROR_CREATE_FROM_COPIED_STRING(message_string), grpc_error_set_int(
GRPC_ERROR_INT_GRPC_STATUS, GRPC_ERROR_CREATE_FROM_COPIED_STRING(
GRPC_STATUS_RESOURCE_EXHAUSTED), 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); calld->call_combiner);
gpr_free(message_string);
return; return;
} }
// Inject callback for receiving a message. // Inject callback for receiving a message.

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

@ -24,8 +24,9 @@
#ifdef GPR_SUPPORT_CHANNELS_FROM_FD #ifdef GPR_SUPPORT_CHANNELS_FROM_FD
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.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/ext/transport/chttp2/transport/chttp2_transport.h"
#include "src/core/lib/channel/channel_args.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); GPR_ASSERT(reserved == nullptr);
grpc_core::ExecCtx exec_ctx; 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_endpoint* server_endpoint =
grpc_tcp_create(grpc_fd_create(fd, name, true), grpc_tcp_create(grpc_fd_create(fd, name.c_str(), true),
grpc_server_get_channel_args(server), name); grpc_server_get_channel_args(server), name.c_str());
gpr_free(name);
const grpc_channel_args* server_args = grpc_server_get_channel_args(server); const grpc_channel_args* server_args = grpc_server_get_channel_args(server);
grpc_transport* transport = grpc_create_chttp2_transport( grpc_transport* transport = grpc_create_chttp2_transport(

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

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

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

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

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

@ -23,9 +23,10 @@
#include <string.h> #include <string.h>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.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/chttp2_transport.h"
#include "src/core/ext/transport/chttp2/transport/frame.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); static_cast<grpc_chttp2_settings_parser*>(p);
const uint8_t* cur = GRPC_SLICE_START_PTR(slice); const uint8_t* cur = GRPC_SLICE_START_PTR(slice);
const uint8_t* end = GRPC_SLICE_END_PTR(slice); const uint8_t* end = GRPC_SLICE_END_PTR(slice);
char* msg;
grpc_chttp2_setting_id id; grpc_chttp2_setting_id id;
if (parser->is_ack) { 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, t->last_new_stream_id, sp->error_value,
grpc_slice_from_static_string("HTTP2 settings error"), grpc_slice_from_static_string("HTTP2 settings error"),
&t->qbuf); &t->qbuf);
gpr_asprintf(&msg, "invalid value %u passed for %s", return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
parser->value, sp->name); absl::StrFormat("invalid value %u passed for %s",
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); parser->value, sp->name)
gpr_free(msg); .c_str());
return err;
} }
} }
if (id == GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE && 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/frame_window_update.h"
#include "src/core/ext/transport/chttp2/transport/internal.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/alloc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpc/support/string_util.h>
grpc_slice grpc_chttp2_window_update_create( grpc_slice grpc_chttp2_window_update_create(
uint32_t id, uint32_t window_update, grpc_transport_one_way_stats* stats) { 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_error* grpc_chttp2_window_update_parser_begin_frame(
grpc_chttp2_window_update_parser* parser, uint32_t length, uint8_t flags) { grpc_chttp2_window_update_parser* parser, uint32_t length, uint8_t flags) {
if (flags || length != 4) { if (flags || length != 4) {
char* msg; return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
gpr_asprintf(&msg, "invalid window update: length=%d, flags=%02x", length, absl::StrFormat("invalid window update: length=%d, flags=%02x", length,
flags); flags)
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); .c_str());
gpr_free(msg);
return err;
} }
parser->byte = 0; parser->byte = 0;
parser->amount = 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. // top bit is reserved and must be ignored.
uint32_t received_update = p->amount & 0x7fffffffu; uint32_t received_update = p->amount & 0x7fffffffu;
if (received_update == 0) { if (received_update == 0) {
char* msg; return GRPC_ERROR_CREATE_FROM_COPIED_STRING(
gpr_asprintf(&msg, "invalid window update bytes: %d", p->amount); absl::StrCat("invalid window update bytes: ", p->amount).c_str());
grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg);
gpr_free(msg);
return err;
} }
GPR_ASSERT(is_last); GPR_ASSERT(is_last);

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

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

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

@ -20,10 +20,13 @@
#include <string.h> #include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/slice_buffer.h> #include <grpc/slice_buffer.h>
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.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_decoder.h"
#include "src/core/ext/transport/chttp2/transport/bin_encoder.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 Convert metadata in a format that Cronet can consume
*/ */
static void convert_metadata_to_cronet_headers( 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, bidirectional_stream_header** pp_headers, size_t* p_num_headers,
const char** method) { const char** method) {
grpc_linked_mdelem* curr = metadata->list.head; 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)) { if (grpc_slice_eq_static_interned(GRPC_MDKEY(mdelem), GRPC_MDSTR_PATH)) {
/* Create URL by appending :path value to the hostname */ /* 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(key);
gpr_free(value); gpr_free(value);
continue; 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_disable_auto_flush(s->cbs, true);
bidirectional_stream_delay_request_headers_until_flush(s->cbs, true); bidirectional_stream_delay_request_headers_until_flush(s->cbs, true);
} }
char* url = nullptr; std::string url;
const char* method = "POST"; const char* method = "POST";
s->header_array.headers = nullptr; s->header_array.headers = nullptr;
convert_metadata_to_cronet_headers( 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, t->host, &url, &s->header_array.headers, &s->header_array.count,
&method); &method);
s->header_array.capacity = s->header_array.count; s->header_array.capacity = s->header_array.count;
CRONET_LOG(GPR_DEBUG, "bidirectional_stream_start(%p, %s)", s->cbs, url); CRONET_LOG(GPR_DEBUG, "bidirectional_stream_start(%p, %s)", s->cbs,
bidirectional_stream_start(s->cbs, url, 0, method, &s->header_array, false); url.c_str());
if (url) { bidirectional_stream_start(s->cbs, url.c_str(), 0, method, &s->header_array,
gpr_free(url); false);
}
unsigned int header_index; unsigned int header_index;
for (header_index = 0; header_index < s->header_array.count; for (header_index = 0; header_index < s->header_array.count;
header_index++) { header_index++) {

@ -146,14 +146,12 @@ const char* severity_string(ChannelTrace::Severity severity) {
Json ChannelTrace::TraceEvent::RenderTraceEvent() const { Json ChannelTrace::TraceEvent::RenderTraceEvent() const {
char* description = grpc_slice_to_c_string(data_); char* description = grpc_slice_to_c_string(data_);
char* ts_str = gpr_format_timespec(timestamp_);
Json::Object object = { Json::Object object = {
{"description", description}, {"description", description},
{"severity", severity_string(severity_)}, {"severity", severity_string(severity_)},
{"timestamp", ts_str}, {"timestamp", gpr_format_timespec(timestamp_)},
}; };
gpr_free(description); gpr_free(description);
gpr_free(ts_str);
if (referenced_entity_ != nullptr) { if (referenced_entity_ != nullptr) {
const bool is_channel = const bool is_channel =
(referenced_entity_->type() == BaseNode::EntityType::kTopLevelChannel || (referenced_entity_->type() == BaseNode::EntityType::kTopLevelChannel ||
@ -171,11 +169,9 @@ Json ChannelTrace::RenderJson() const {
if (max_event_memory_ == 0) { if (max_event_memory_ == 0) {
return Json(); // JSON null return Json(); // JSON null
} }
char* ts_str = gpr_format_timespec(time_created_);
Json::Object object = { Json::Object object = {
{"creationTimestamp", ts_str}, {"creationTimestamp", gpr_format_timespec(time_created_)},
}; };
gpr_free(ts_str);
if (num_events_logged_ > 0) { if (num_events_logged_ > 0) {
object["numEventsLogged"] = std::to_string(num_events_logged_); 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_timespec ts = gpr_convert_clock_type(
gpr_cycle_counter_to_time(data.last_call_started_cycle), gpr_cycle_counter_to_time(data.last_call_started_cycle),
GPR_CLOCK_REALTIME); GPR_CLOCK_REALTIME);
char* ts_str = gpr_format_timespec(ts); (*object)["lastCallStartedTimestamp"] = gpr_format_timespec(ts);
(*object)["lastCallStartedTimestamp"] = ts_str;
gpr_free(ts_str);
} }
if (data.calls_succeeded != 0) { if (data.calls_succeeded != 0) {
(*object)["callsSucceeded"] = std::to_string(data.calls_succeeded); (*object)["callsSucceeded"] = std::to_string(data.calls_succeeded);
@ -456,9 +454,7 @@ Json SocketNode::RenderJson() {
ts = gpr_convert_clock_type( ts = gpr_convert_clock_type(
gpr_cycle_counter_to_time(last_local_stream_created_cycle), gpr_cycle_counter_to_time(last_local_stream_created_cycle),
GPR_CLOCK_REALTIME); GPR_CLOCK_REALTIME);
char* ts_str = gpr_format_timespec(ts); data["lastLocalStreamCreatedTimestamp"] = gpr_format_timespec(ts);
data["lastLocalStreamCreatedTimestamp"] = ts_str;
gpr_free(ts_str);
} }
gpr_cycle_counter last_remote_stream_created_cycle = gpr_cycle_counter last_remote_stream_created_cycle =
last_remote_stream_created_cycle_.Load(MemoryOrder::RELAXED); last_remote_stream_created_cycle_.Load(MemoryOrder::RELAXED);
@ -466,9 +462,7 @@ Json SocketNode::RenderJson() {
ts = gpr_convert_clock_type( ts = gpr_convert_clock_type(
gpr_cycle_counter_to_time(last_remote_stream_created_cycle), gpr_cycle_counter_to_time(last_remote_stream_created_cycle),
GPR_CLOCK_REALTIME); GPR_CLOCK_REALTIME);
char* ts_str = gpr_format_timespec(ts); data["lastRemoteStreamCreatedTimestamp"] = gpr_format_timespec(ts);
data["lastRemoteStreamCreatedTimestamp"] = ts_str;
gpr_free(ts_str);
} }
} }
int64_t streams_succeeded = streams_succeeded_.Load(MemoryOrder::RELAXED); int64_t streams_succeeded = streams_succeeded_.Load(MemoryOrder::RELAXED);
@ -486,9 +480,7 @@ Json SocketNode::RenderJson() {
gpr_cycle_counter_to_time( gpr_cycle_counter_to_time(
last_message_sent_cycle_.Load(MemoryOrder::RELAXED)), last_message_sent_cycle_.Load(MemoryOrder::RELAXED)),
GPR_CLOCK_REALTIME); GPR_CLOCK_REALTIME);
char* ts_str = gpr_format_timespec(ts); data["lastMessageSentTimestamp"] = gpr_format_timespec(ts);
data["lastMessageSentTimestamp"] = ts_str;
gpr_free(ts_str);
} }
int64_t messages_received = messages_received_.Load(MemoryOrder::RELAXED); int64_t messages_received = messages_received_.Load(MemoryOrder::RELAXED);
if (messages_received != 0) { if (messages_received != 0) {
@ -497,9 +489,7 @@ Json SocketNode::RenderJson() {
gpr_cycle_counter_to_time( gpr_cycle_counter_to_time(
last_message_received_cycle_.Load(MemoryOrder::RELAXED)), last_message_received_cycle_.Load(MemoryOrder::RELAXED)),
GPR_CLOCK_REALTIME); GPR_CLOCK_REALTIME);
char* ts_str = gpr_format_timespec(ts); data["lastMessageReceivedTimestamp"] = gpr_format_timespec(ts);
data["lastMessageReceivedTimestamp"] = ts_str;
gpr_free(ts_str);
} }
int64_t keepalives_sent = keepalives_sent_.Load(MemoryOrder::RELAXED); int64_t keepalives_sent = keepalives_sent_.Load(MemoryOrder::RELAXED);
if (keepalives_sent != 0) { if (keepalives_sent != 0) {

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

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

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

@ -26,6 +26,8 @@
#include <stdbool.h> #include <stdbool.h>
#include <stddef.h> #include <stddef.h>
#include <string>
/* String utility functions */ /* String utility functions */
/* Flags for gpr_dump function. */ /* 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, void gpr_string_split(const char* input, const char* sep, char*** strs,
size_t* nstrs); 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: more specifically, follows:
https://developers.google.com/protocol-buffers/docs/proto3#json https://developers.google.com/protocol-buffers/docs/proto3#json
Uses RFC 3339, where generated output will always be Z-normalized and uses Uses RFC 3339, where generated output will always be Z-normalized and uses
0, 3, 6 or 9 fractional digits. */ 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 /** Case insensitive string comparison... return <0 if lower(a)<lower(b), ==0 if
lower(a)==lower(b), >0 if lower(a)>lower(b) */ lower(a)==lower(b), >0 if lower(a)>lower(b) */

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

@ -22,6 +22,10 @@
#include <string.h> #include <string.h>
#include <string>
#include "absl/strings/str_format.h"
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpc/support/string_util.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_ERROR_CREATE_FROM_STATIC_STRING("Failed HTTP/1 client request");
} }
grpc_resolved_address* addr = &req->addresses->addrs[req->next_address - 1]; 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_add_child(
req->overall_error, req->overall_error,
grpc_error_set_str(error, GRPC_ERROR_STR_TARGET_ADDRESS, 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) { static void do_read(internal_request* req) {
@ -266,15 +270,14 @@ void grpc_httpcli_get(grpc_httpcli_context* context,
grpc_resource_quota* resource_quota, grpc_resource_quota* resource_quota,
const grpc_httpcli_request* request, grpc_millis deadline, const grpc_httpcli_request* request, grpc_millis deadline,
grpc_closure* on_done, grpc_httpcli_response* response) { grpc_closure* on_done, grpc_httpcli_response* response) {
char* name;
if (g_get_override && g_get_override(request, deadline, on_done, response)) { if (g_get_override && g_get_override(request, deadline, on_done, response)) {
return; 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, 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)); grpc_httpcli_format_get_request(request));
gpr_free(name);
} }
void grpc_httpcli_post(grpc_httpcli_context* context, 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, const char* body_bytes, size_t body_size,
grpc_millis deadline, grpc_closure* on_done, grpc_millis deadline, grpc_closure* on_done,
grpc_httpcli_response* response) { grpc_httpcli_response* response) {
char* name;
if (g_post_override && g_post_override(request, body_bytes, body_size, if (g_post_override && g_post_override(request, body_bytes, body_size,
deadline, on_done, response)) { deadline, on_done, response)) {
return; 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( internal_request_begin(
context, pollent, resource_quota, request, deadline, on_done, response, context, pollent, resource_quota, request, deadline, on_done, response,
name, grpc_httpcli_format_post_request(request, body_bytes, body_size)); name.c_str(),
gpr_free(name); grpc_httpcli_format_post_request(request, body_bytes, body_size));
} }
void grpc_httpcli_set_override(grpc_httpcli_get_override get, void grpc_httpcli_set_override(grpc_httpcli_get_override get,

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

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

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

@ -38,14 +38,15 @@
#include <sys/socket.h> #include <sys/socket.h>
#include <unistd.h> #include <unistd.h>
#include <string>
#include <vector> #include <vector>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h" #include "absl/strings/str_format.h"
#include "absl/strings/str_join.h" #include "absl/strings/str_join.h"
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/cpu.h> #include <grpc/support/cpu.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/debug/stats.h" #include "src/core/lib/debug/stats.h"
#include "src/core/lib/gpr/string.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; new_fd->freelist_next = nullptr;
char* fd_name; std::string fd_name = absl::StrCat(name, " fd=", fd);
gpr_asprintf(&fd_name, "%s fd=%d", name, fd); grpc_iomgr_register_object(&new_fd->iomgr_object, fd_name.c_str());
grpc_iomgr_register_object(&new_fd->iomgr_object, fd_name);
fork_fd_list_add_grpc_fd(new_fd); fork_fd_list_add_grpc_fd(new_fd);
#ifndef NDEBUG #ifndef NDEBUG
if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) { 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 #endif
gpr_free(fd_name);
struct epoll_event ev; struct epoll_event ev;
ev.events = static_cast<uint32_t>(EPOLLIN | EPOLLOUT | EPOLLET); ev.events = static_cast<uint32_t>(EPOLLIN | EPOLLOUT | EPOLLET);

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

@ -32,9 +32,12 @@
#include <sys/socket.h> #include <sys/socket.h>
#include <unistd.h> #include <unistd.h>
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/debug/stats.h" #include "src/core/lib/debug/stats.h"
#include "src/core/lib/gpr/murmur_hash.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; r->released = 0;
gpr_atm_no_barrier_store(&r->pollhup, 0); gpr_atm_no_barrier_store(&r->pollhup, 0);
char* name2; std::string name2 = absl::StrCat(name, " fd=", fd);
gpr_asprintf(&name2, "%s fd=%d", name, fd); grpc_iomgr_register_object(&r->iomgr_object, name2.c_str());
grpc_iomgr_register_object(&r->iomgr_object, name2);
gpr_free(name2);
fork_fd_list_add_grpc_fd(r); fork_fd_list_add_grpc_fd(r);
return r; return r;
} }

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

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

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

@ -24,11 +24,13 @@
#include <inttypes.h> #include <inttypes.h>
#include <string.h> #include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h" #include "absl/strings/str_format.h"
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/host_port.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); grpc_sockaddr_set_port(out, port);
} }
char* grpc_sockaddr_to_uri(const grpc_resolved_address* resolved_addr) { std::string grpc_sockaddr_to_uri(const grpc_resolved_address* resolved_addr) {
if (resolved_addr->len == 0) return nullptr; if (resolved_addr->len == 0) return "";
grpc_resolved_address addr_normalized; grpc_resolved_address addr_normalized;
if (grpc_sockaddr_is_v4mapped(resolved_addr, &addr_normalized)) { if (grpc_sockaddr_is_v4mapped(resolved_addr, &addr_normalized)) {
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 = std::string path =
grpc_sockaddr_to_string(resolved_addr, false /* normalize */); grpc_sockaddr_to_string(resolved_addr, false /* normalize */);
char* uri_str = nullptr; std::string uri_str;
if (scheme != nullptr) { if (scheme != nullptr) {
gpr_asprintf(&uri_str, "%s:%s", scheme, path.c_str()); uri_str = absl::StrCat(scheme, ":", path);
} }
return uri_str; 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); void grpc_string_to_sockaddr(grpc_resolved_address* out, char* addr, int port);
/* Returns the URI string corresponding to \a addr */ /* 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 */ /* Returns the URI scheme corresponding to \a addr */
const char* grpc_sockaddr_get_uri_scheme(const grpc_resolved_address* addr); const char* grpc_sockaddr_get_uri_scheme(const grpc_resolved_address* addr);

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

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

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

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

@ -39,6 +39,7 @@
#include "src/core/lib/iomgr/tcp_client.h" #include "src/core/lib/iomgr/tcp_client.h"
#include "src/core/lib/iomgr/tcp_windows.h" #include "src/core/lib/iomgr/tcp_windows.h"
#include "src/core/lib/iomgr/timer.h" #include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/slice/slice_internal.h"
struct async_connect { struct async_connect {
grpc_closure* on_done; grpc_closure* on_done;
@ -46,12 +47,13 @@ struct async_connect {
grpc_winsocket* socket; grpc_winsocket* socket;
grpc_timer alarm; grpc_timer alarm;
grpc_closure on_alarm; grpc_closure on_alarm;
char* addr_name; std::string addr_name;
int refs; int refs;
grpc_closure on_connect; grpc_closure on_connect;
grpc_endpoint** endpoint; grpc_endpoint** endpoint;
grpc_channel_args* channel_args; grpc_channel_args* channel_args;
}; };
static void async_connect_unlock_and_cleanup(async_connect* ac, static void async_connect_unlock_and_cleanup(async_connect* ac,
grpc_winsocket* socket) { grpc_winsocket* socket) {
int done = (--ac->refs == 0); int done = (--ac->refs == 0);
@ -59,8 +61,7 @@ static void async_connect_unlock_and_cleanup(async_connect* ac,
if (done) { if (done) {
grpc_channel_args_destroy(ac->channel_args); grpc_channel_args_destroy(ac->channel_args);
gpr_mu_destroy(&ac->mu); gpr_mu_destroy(&ac->mu);
gpr_free(ac->addr_name); delete ac;
gpr_free(ac);
} }
if (socket != NULL) grpc_winsocket_destroy(socket); 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"); error = GRPC_WSA_ERROR(WSAGetLastError(), "ConnectEx");
closesocket(socket->socket); closesocket(socket->socket);
} else { } 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; socket = NULL;
} }
} else { } else {
@ -131,13 +132,13 @@ static void tcp_connect(grpc_closure* on_done, grpc_endpoint** endpoint,
int status; int status;
grpc_resolved_address addr6_v4mapped; grpc_resolved_address addr6_v4mapped;
grpc_resolved_address local_address; grpc_resolved_address local_address;
async_connect* ac;
grpc_winsocket* socket = NULL; grpc_winsocket* socket = NULL;
LPFN_CONNECTEX ConnectEx; LPFN_CONNECTEX ConnectEx;
GUID guid = WSAID_CONNECTEX; GUID guid = WSAID_CONNECTEX;
DWORD ioctl_num_bytes; DWORD ioctl_num_bytes;
grpc_winsocket_callback_info* info; grpc_winsocket_callback_info* info;
grpc_error* error = GRPC_ERROR_NONE; grpc_error* error = GRPC_ERROR_NONE;
async_connect* ac = NULL;
*endpoint = 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->on_done = on_done;
ac->socket = socket; ac->socket = socket;
gpr_mu_init(&ac->mu); gpr_mu_init(&ac->mu);
@ -211,13 +212,12 @@ static void tcp_connect(grpc_closure* on_done, grpc_endpoint** endpoint,
failure: failure:
GPR_ASSERT(error != GRPC_ERROR_NONE); 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* final_error =
grpc_error_set_str(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( grpc_error_set_str(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
"Failed to connect", &error, 1), "Failed to connect", &error, 1),
GRPC_ERROR_STR_TARGET_ADDRESS, GRPC_ERROR_STR_TARGET_ADDRESS,
grpc_slice_from_copied_string( grpc_slice_from_cpp_string(std::move(target_uri)));
target_uri == nullptr ? "NULL" : target_uri));
GRPC_ERROR_UNREF(error); GRPC_ERROR_UNREF(error);
if (socket != NULL) { if (socket != NULL) {
grpc_winsocket_destroy(socket); 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_endpoint* custom_tcp_endpoint_create(grpc_custom_socket* socket,
grpc_resource_quota* resource_quota, grpc_resource_quota* resource_quota,
char* peer_string) { const char* peer_string) {
custom_tcp_endpoint* tcp = custom_tcp_endpoint* tcp =
(custom_tcp_endpoint*)gpr_malloc(sizeof(custom_tcp_endpoint)); (custom_tcp_endpoint*)gpr_malloc(sizeof(custom_tcp_endpoint));
grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; 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_endpoint* custom_tcp_endpoint_create(grpc_custom_socket* socket,
grpc_resource_quota* resource_quota, grpc_resource_quota* resource_quota,
char* peer_string); const char* peer_string);
#endif /* GRPC_CORE_LIB_IOMGR_TCP_CUSTOM_H */ #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_tcp_server_acceptor*)gpr_malloc(sizeof(*acceptor));
grpc_endpoint* ep = nullptr; grpc_endpoint* ep = nullptr;
grpc_resolved_address peer_name; grpc_resolved_address peer_name;
char* peer_name_string; std::string peer_name_string;
grpc_error* err; grpc_error* err;
peer_name_string = nullptr;
memset(&peer_name, 0, sizeof(grpc_resolved_address)); memset(&peer_name, 0, sizeof(grpc_resolved_address));
peer_name.len = GRPC_MAX_SOCKADDR_SIZE; peer_name.len = GRPC_MAX_SOCKADDR_SIZE;
err = grpc_custom_socket_vtable->getpeername( 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); GRPC_ERROR_UNREF(err);
} }
if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) { if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
if (peer_name_string) { gpr_log(GPR_INFO, "SERVER_CONNECT: %p accepted connection: %s", sp->server,
gpr_log(GPR_INFO, "SERVER_CONNECT: %p accepted connection: %s", peer_name_string.c_str());
sp->server, peer_name_string);
} else {
gpr_log(GPR_INFO, "SERVER_CONNECT: %p accepted connection", sp->server);
}
} }
ep = custom_tcp_endpoint_create(socket, sp->server->resource_quota, ep = custom_tcp_endpoint_create(socket, sp->server->resource_quota,
peer_name_string); peer_name_string.c_str());
acceptor->from_server = sp->server; acceptor->from_server = sp->server;
acceptor->port_index = sp->port_index; acceptor->port_index = sp->port_index;
acceptor->fd_index = 0; acceptor->fd_index = 0;
acceptor->external_connection = false; acceptor->external_connection = false;
sp->server->on_accept_cb(sp->server->on_accept_cb_arg, ep, nullptr, acceptor); 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, static void custom_accept_callback(grpc_custom_socket* socket,

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

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

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

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

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

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

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

@ -21,6 +21,8 @@
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <string>
#include "src/core/lib/iomgr/port.h" #include "src/core/lib/iomgr/port.h"
#include <grpc/support/string_util.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( void grpc_unlink_if_unix_domain_socket(
const grpc_resolved_address* resolved_addr); 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); const grpc_resolved_address* resolved_addr);
#endif /* GRPC_CORE_LIB_IOMGR_UNIX_SOCKETS_POSIX_H */ #endif /* GRPC_CORE_LIB_IOMGR_UNIX_SOCKETS_POSIX_H */

@ -22,6 +22,8 @@
#ifndef GRPC_HAVE_UNIX_SOCKET #ifndef GRPC_HAVE_UNIX_SOCKET
#include <string>
#include <grpc/support/log.h> #include <grpc/support/log.h>
void grpc_create_socketpair_if_unix(int sv[2]) { 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) {} 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) { std::string grpc_sockaddr_to_uri_unix_if_possible(
return NULL; const grpc_resolved_address* addr) {
return "";
} }
#endif #endif

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

@ -23,6 +23,8 @@
#include <string.h> #include <string.h>
#include <string>
#include <grpc/grpc.h> #include <grpc/grpc.h>
#include <grpc/grpc_security.h> #include <grpc/grpc_security.h>
#include <grpc/support/sync.h> #include <grpc/support/sync.h>
@ -79,13 +81,13 @@ typedef enum {
/* --- Google utils --- */ /* --- Google utils --- */
/* It is the caller's responsibility to gpr_free the result if not NULL. */ /* 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. */ /* 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 */ /* 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( void grpc_override_well_known_credentials_path_getter(
grpc_well_known_credentials_path_getter 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 "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/alloc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/env.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) { std::string grpc_get_well_known_google_credentials_file_path_impl(void) {
char* result = nullptr;
char* base = gpr_getenv(GRPC_GOOGLE_CREDENTIALS_PATH_ENV_VAR); char* base = gpr_getenv(GRPC_GOOGLE_CREDENTIALS_PATH_ENV_VAR);
if (base == nullptr) { if (base == nullptr) {
gpr_log(GPR_ERROR, "Could not get " GRPC_GOOGLE_CREDENTIALS_PATH_ENV_VAR gpr_log(GPR_ERROR, "Could not get " GRPC_GOOGLE_CREDENTIALS_PATH_ENV_VAR
" environment variable."); " 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); gpr_free(base);
return result; return result;
} }

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

@ -23,8 +23,13 @@
#include <inttypes.h> #include <inttypes.h>
#include <string.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.h"
#include "src/core/lib/gprpp/ref_counted_ptr.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 "src/core/lib/surface/api_trace.h"
#include <grpc/support/alloc.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_, jwt = grpc_jwt_encode_and_sign(&key_, context.service_url, jwt_lifetime_,
nullptr); nullptr);
if (jwt != nullptr) { if (jwt != nullptr) {
char* md_value; std::string md_value = absl::StrCat("Bearer ", jwt);
gpr_asprintf(&md_value, "Bearer %s", jwt);
gpr_free(jwt); gpr_free(jwt);
cached_.jwt_expiration = cached_.jwt_expiration =
gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), jwt_lifetime_); gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), jwt_lifetime_);
cached_.service_url = gpr_strdup(context.service_url); cached_.service_url = gpr_strdup(context.service_url);
cached_.jwt_md = grpc_mdelem_from_slices( cached_.jwt_md = grpc_mdelem_from_slices(
grpc_slice_from_static_string(GRPC_AUTHORIZATION_METADATA_KEY), grpc_slice_from_static_string(GRPC_AUTHORIZATION_METADATA_KEY),
grpc_slice_from_copied_string(md_value)); grpc_slice_from_cpp_string(std::move(md_value)));
gpr_free(md_value);
jwt_md = GRPC_MDELEM_REF(cached_.jwt_md); jwt_md = GRPC_MDELEM_REF(cached_.jwt_md);
} }
gpr_mu_unlock(&cache_mu_); gpr_mu_unlock(&cache_mu_);

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

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

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

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

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

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

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

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

@ -156,7 +156,7 @@ class NewWithLenSliceRefcount {
/** grpc_slice_from_moved_(string|buffer) ref count .*/ /** grpc_slice_from_moved_(string|buffer) ref count .*/
class MovedStringSliceRefCount { class MovedStringSliceRefCount {
public: public:
MovedStringSliceRefCount(grpc_core::UniquePtr<char>&& str) explicit MovedStringSliceRefCount(grpc_core::UniquePtr<char>&& str)
: base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this, : base_(grpc_slice_refcount::Type::REGULAR, &refs_, Destroy, this,
&base_), &base_),
str_(std::move(str)) {} str_(std::move(str)) {}
@ -173,6 +173,26 @@ class MovedStringSliceRefCount {
grpc_core::UniquePtr<char> str_; 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 } // namespace grpc_core
grpc_slice grpc_slice_new_with_len(void* p, size_t len, 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); 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 { namespace {
class MallocRefCount { 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, grpc_slice grpc_slice_from_moved_buffer(grpc_core::UniquePtr<char> p,
size_t len); size_t len);
grpc_slice grpc_slice_from_moved_string(grpc_core::UniquePtr<char> p); 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 // Returns the memory used by this slice, not counting the slice structure
// itself. This means that inlined and slices from static strings will return // itself. This means that inlined and slices from static strings will return

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading…
Cancel
Save