1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // Common helper functions/classes used both in the host and device forwarder.
7 #ifndef TOOLS_ANDROID_FORWARDER2_COMMON_H_
8 #define TOOLS_ANDROID_FORWARDER2_COMMON_H_
14 #include "base/basictypes.h"
15 #include "base/compiler_specific.h"
16 #include "base/logging.h"
17 #include "base/posix/eintr_wrapper.h"
19 // Preserving errno for Close() is important because the function is very often
20 // used in cleanup code, after an error occurred, and it is very easy to pass an
21 // invalid file descriptor to close() in this context, or more rarely, a
22 // spurious signal might make close() return -1 + setting errno to EINTR,
23 // masking the real reason for the original error. This leads to very unpleasant
24 // debugging sessions.
25 #define PRESERVE_ERRNO_HANDLE_EINTR(Func) \
27 int local_errno = errno; \
28 (void) HANDLE_EINTR(Func); \
29 errno = local_errno; \
32 // Wrapper around RAW_LOG() which is signal-safe. The only purpose of this macro
33 // is to avoid documenting uses of RawLog().
34 #define SIGNAL_SAFE_LOG(Level, Msg) \
37 namespace forwarder2
{
39 // Note that the two following functions are not signal-safe.
41 // Chromium logging-aware implementation of libc's perror().
42 void PError(const char* msg
);
44 // Closes the provided file descriptor and logs an error if it failed.
47 // Helps build a formatted C-string allocated in a fixed-size array. This is
48 // useful in signal handlers where base::StringPrintf() can't be used safely
49 // (due to its use of LOG()).
50 template <int BufferSize
>
51 class FixedSizeStringBuilder
{
53 FixedSizeStringBuilder() {
57 const char* buffer() const { return buffer_
; }
64 // Returns the number of bytes appended to the underlying buffer or -1 if it
66 int Append(const char* format
, ...) PRINTF_FORMAT(/* + 1 for 'this' */ 2, 3) {
67 if (write_ptr_
>= buffer_
+ BufferSize
)
71 const int bytes_written
= vsnprintf(
72 write_ptr_
, BufferSize
- (write_ptr_
- buffer_
), format
, ap
);
74 if (bytes_written
> 0)
75 write_ptr_
+= bytes_written
;
81 char buffer_
[BufferSize
];
83 static_assert(BufferSize
>= 1, "size of buffer must be at least one");
84 DISALLOW_COPY_AND_ASSIGN(FixedSizeStringBuilder
);
87 } // namespace forwarder2
89 #endif // TOOLS_ANDROID_FORWARDER2_COMMON_H_