Os: add Write() method
If we're going to dump log messages, we need to
be able to write to a file descriptor. Plumb up
write(), via Os::Write().
Bug: 31997280
Test: ./runtests.sh
Change-Id: I0ebdf2f33dd1f458116e9bbf51ae82e51d107d42
diff --git a/os.cpp b/os.cpp
index b190fec..d437066 100644
--- a/os.cpp
+++ b/os.cpp
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+#include <errno.h>
+
#include <algorithm>
#include <cstdint>
@@ -56,5 +58,28 @@
return now_timestamp;
}
+std::tuple<size_t, Os::Errno> Os::Write(int fd, const void* buf,
+ size_t buflen) {
+ // write() takes a size_t, but returns an ssize_t. That means that the
+ // largest successful write that write() can report is the maximal ssize_t.
+ // Passing a larger |buflen| risks mistakenly reporting a truncated write.
+ CHECK(buflen <= GetMaxVal<ssize_t>());
+
+ const ssize_t res = raw_os_->Write(fd, buf, buflen);
+ if (res < 0) {
+ return {0, errno};
+ }
+
+ CHECK(res <=
+ SAFELY_CLAMP(buflen, ssize_t, 0,
+ GetMaxVal<ssize_t>())); // Abort on buffer overflow.
+
+ // Note that |res| may be less than buflen. However, a) a short write is
+ // not an error, and b) |errno| may be stale, as |errno| is only guaranteed to
+ // be set if an error occurred. Hence, we return Errno of 0 unconditionally.
+ // See http://yarchive.net/comp/linux/write_error_return.html
+ return {res, 0};
+}
+
} // namespace wifilogd
} // namespace android