Initial import
authorFelix Fietkau <nbd@nbd.name>
Sun, 12 Nov 2023 18:11:20 +0000 (19:11 +0100)
committerFelix Fietkau <nbd@nbd.name>
Mon, 13 Nov 2023 18:02:34 +0000 (19:02 +0100)
Signed-off-by: Felix Fietkau <nbd@nbd.name>
18 files changed:
.gitignore [new file with mode: 0644]
CMakeLists.txt [new file with mode: 0644]
README.md [new file with mode: 0644]
client.c [new file with mode: 0644]
examples/test-source.c [new file with mode: 0644]
examples/test-source.uc [new file with mode: 0755]
lib-pcap.c [new file with mode: 0644]
lib-remote.c [new file with mode: 0644]
lib-ucode.c [new file with mode: 0644]
lib.c [new file with mode: 0644]
main.c [new file with mode: 0644]
priv.h [new file with mode: 0644]
ring.c [new file with mode: 0644]
server.h [new file with mode: 0644]
ubus.c [new file with mode: 0644]
udebug-cli [new file with mode: 0755]
udebug-pcap.h [new file with mode: 0644]
udebug.h [new file with mode: 0644]

diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..a05f812
--- /dev/null
@@ -0,0 +1,13 @@
+Makefile
+CMakeCache.txt
+CMakeFiles
+.*
+*.cmake
+*.so
+*.dylib
+*.pcap
+udebugd
+test-source
+test-receiver
+test-pcap
+install_manifest.txt
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644 (file)
index 0000000..a187f78
--- /dev/null
@@ -0,0 +1,44 @@
+cmake_minimum_required(VERSION 3.3)
+
+PROJECT(udebugd C)
+
+ADD_DEFINITIONS(-O2 -Wall -fwrapv -Werror --std=gnu99 -g3 -Wmissing-declarations -DRUNSTATEDIR="${RUNSTATEDIR}")
+FIND_LIBRARY(ubus NAMES ubus)
+FIND_LIBRARY(ubox NAMES ubox)
+
+FIND_PATH(ubus_include_dir NAMES libubus.h)
+FIND_PATH(uloop_include_dir NAMES libubox/uloop.h)
+FIND_PATH(ucode_include_dir NAMES ucode/module.h)
+INCLUDE_DIRECTORIES(${uloop_include_dir} ${ubus_include_dir} ${ucode_include_dir})
+
+IF(APPLE)
+  SET(UCODE_MODULE_LINK_OPTIONS "LINKER:-undefined,dynamic_lookup")
+ENDIF()
+
+ADD_LIBRARY(udebug SHARED lib.c lib-pcap.c lib-remote.c)
+IF(ABIVERSION)
+  SET_TARGET_PROPERTIES(udebug PROPERTIES VERSION ${ABIVERSION})
+ENDIF()
+TARGET_LINK_LIBRARIES(udebug ubox)
+
+ADD_EXECUTABLE(udebugd main.c client.c ring.c ubus.c)
+TARGET_LINK_LIBRARIES(udebugd udebug ubox ${ubus})
+
+ADD_LIBRARY(ucode_lib MODULE lib-ucode.c)
+SET_TARGET_PROPERTIES(ucode_lib PROPERTIES OUTPUT_NAME udebug PREFIX "")
+TARGET_LINK_OPTIONS(ucode_lib PRIVATE ${UCODE_MODULE_LINK_OPTIONS})
+TARGET_LINK_LIBRARIES(ucode_lib ${ubox} udebug)
+
+INSTALL(FILES udebug.h udebug-pcap.h
+       DESTINATION include
+)
+INSTALL(FILES udebug-cli
+       DESTINATION sbin
+)
+INSTALL(TARGETS udebugd udebug
+       RUNTIME DESTINATION sbin
+       LIBRARY DESTINATION lib
+)
+INSTALL(TARGETS ucode_lib
+       LIBRARY DESTINATION lib/ucode
+)
diff --git a/README.md b/README.md
new file mode 100644 (file)
index 0000000..93a8264
--- /dev/null
+++ b/README.md
@@ -0,0 +1,111 @@
+# udebug - OpenWrt debugging infrastructure
+
+udebug assists whole-system debugging by making it easy to provide ring buffers
+with debug data and make them accessible through a unified API.
+Through the CLI, you can either create snapshots of data with a specific duration,
+or stream data in real time. The data itself is stored in .pcapng files, which can
+contain a mix of packets and log messages.
+
+## libudebug C API
+
+#### `void udebug_init(struct udebug *ctx)`
+
+Initializes the udebug context. Must be called before adding buffers.
+
+#### `int udebug_connect(struct udebug *ctx, const char *path)`
+
+Connect to udebugd and submit any buffers that were added using `udebug_buf_add`.
+
+#### `void udebug_auto_connect(struct udebug *ctx, const char *path)`
+
+Connects and automatically reconnects to udebugd. Uses uloop and calls `udebug_add_uloop`.
+
+#### `void udebug_free(struct udebug *ctx)`
+
+Frees the udebug context and all added created buffers.
+
+#### `int udebug_buf_init(struct udebug_buf *buf, size_t entries, size_t size)`
+
+Allocates a buffer with a given size. Entries and size are rounded up internally to the
+nearest power-of-2.
+
+#### `int udebug_buf_add(struct udebug *ctx, struct udebug_buf *buf, const struct udebug_buf_meta *meta);`
+
+Submits the buffer to udebugd and makes it visible.
+
+#### `void udebug_buf_free(struct udebug_buf *buf)`
+
+Removes the buffer from udebugd and frees it.
+
+#### `void udebug_entry_init(struct udebug_buf *buf)`
+
+Initializes a new entry on the ring buffer.
+
+#### `void *udebug_entry_append(struct udebug_buf *buf, const void *data, uint32_t len)`
+
+Appends data to the ring buffer. When called with data == NULL, space is only
+reserved, and the return value provides a pointer with len bytes that can be
+written to.
+
+#### `int udebug_entry_printf(struct udebug_buf *buf, const char *fmt, ...)`
+
+Appends a string to the buffer, based on format string + arguments (like printf)
+
+#### `int udebug_entry_vprintf(struct udebug_buf *buf, const char *fmt, va_list ap)`
+
+Like `udebug_entry_printf()`
+
+#### `void udebug_entry_add(struct udebug_buf *buf)`
+
+Finalizes and publishes the entry on the ring buffer.
+
+### Simple example
+
+```
+static struct udebug ud;
+static struct udebug_buf udb;
+
+/* ... */
+
+uloop_init();
+udebug_init(&ud);
+udebug_auto_connect(&ud, NULL);
+
+static const struct udebug_buf_meta buf_meta = {
+       .name = "counter",
+       .format = UDEBUG_FORMAT_STRING,
+};
+
+int entries = 128;
+int data_size = 1024;
+
+udebug_buf_init(&udb, entries, data_size);
+udebug_buf_add(&ud, &udb, &buf_meta);
+
+/* ... */
+
+udebug_entry_init(&udb); // initialize entry
+udebug_entry_printf(&udb, "count=%d", count++);
+udebug_entry_add(&udb); // finalize the entry
+
+```
+
+## udebug CLI
+
+```
+Usage: udebug-cli [<options>] <command> [<args>]
+
+  Options:
+    -f                          Ignore errors on opening rings
+    -d <duration>:              Only fetch data up to <duration> seconds old
+    -o <file>|-                 Set output file for snapshot/stream (or '-' for stdout)
+    -i <process>[:<name>]       Select debug buffer for snapshot/stream
+    -s <path>                   Use udebug socket <path>
+    -q                          Suppress warnings/error messages
+
+  Commands:
+    list:                       List available debug buffers
+    snapshot:                   Create a pcapng snapshot of debug buffers
+
+```
+
diff --git a/client.c b/client.c
new file mode 100644 (file)
index 0000000..1fc90d8
--- /dev/null
+++ b/client.c
@@ -0,0 +1,327 @@
+#define _GNU_SOURCE
+#include <sys/un.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+#include <string.h>
+#include <stdlib.h>
+#include <libgen.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <poll.h>
+
+#ifdef linux
+#include <linux/sockios.h>
+#endif
+#ifdef __APPLE__
+#include <libproc.h>
+#endif
+
+#include "server.h"
+
+#define UDEBUG_SNDBUF  65536
+
+static LIST_HEAD(clients);
+
+static void client_send_msg(struct client *cl, struct udebug_client_msg *data, int fd)
+{
+       uint8_t fd_buf[CMSG_SPACE(sizeof(int))] = { 0 };
+       struct iovec iov = {
+               .iov_base = data,
+               .iov_len = sizeof(*data),
+       };
+       struct msghdr msg = {
+               .msg_control = fd_buf,
+               .msg_controllen = sizeof(fd_buf),
+               .msg_iov = &iov,
+               .msg_iovlen = 1,
+       };
+       struct cmsghdr *cmsg;
+       int buffered = 0;
+       int *pfd;
+       int len;
+
+#ifdef linux
+       ioctl(cl->fd.fd, SIOCOUTQ, &buffered);
+#elif defined(__APPLE__)
+       socklen_t slen = sizeof(buffered);
+       getsockopt(cl->fd.fd, SOL_SOCKET, SO_NWRITE, &buffered, &slen);
+#endif
+
+       DC(3, cl, "send msg type=%d len=%d, fd=%d",
+         data->type, (unsigned int)iov.iov_len, fd);
+
+       if (buffered > UDEBUG_SNDBUF / 2) {
+               DC(3, cl, "skip message due to limited buffer size");
+               return;
+       }
+
+       if (fd >= 0) {
+               cmsg = CMSG_FIRSTHDR(&msg);
+               cmsg->cmsg_type = SCM_RIGHTS;
+               cmsg->cmsg_level = SOL_SOCKET;
+               cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+               msg.msg_controllen = cmsg->cmsg_len;
+
+               pfd = (int *)CMSG_DATA(cmsg);
+               *pfd = fd;
+       } else {
+               msg.msg_control = NULL;
+               msg.msg_controllen = 0;
+       }
+
+       do {
+               len = sendmsg(cl->fd.fd, &msg, 0);
+       } while (len < 0 && errno == EINTR);
+}
+
+static int client_alloc_notify_id(void)
+{
+       struct client *cl;
+       uint32_t mask = 0;
+
+       list_for_each_entry(cl, &clients, list)
+               if (cl->notify_id >= 0)
+                       mask |= 1 << cl->notify_id;
+
+       for (int i = 0; i < 32; i++, mask >>= 1)
+               if (!(mask & 1))
+                       return i;
+
+       return 31;
+}
+
+static void client_msg_get_handle(struct client *cl)
+{
+       struct udebug_client_msg msg = {
+               .type = CL_MSG_GET_HANDLE,
+       };
+
+       if (cl->notify_id < 0 && cl->uid == 0)
+               cl->notify_id = client_alloc_notify_id();
+
+       msg.id = cl->notify_id;
+       client_send_msg(cl, &msg, -1);
+}
+
+static void client_msg_ring_get(struct client *cl, uint32_t id)
+{
+       struct udebug_client_msg msg = {
+               .type = CL_MSG_RING_GET,
+               .id = id,
+       };
+       struct client_ring *r = ring_get_by_id(id);
+       int fd = -1;
+
+       if (!r || cl->uid != 0) {
+               DC(2, cl, "could not get ring %x", id);
+               goto out;
+       }
+
+       fd = r->fd;
+       msg.ring_size = r->ring_size;
+       msg.data_size = r->data_size;
+
+out:
+       client_send_msg(cl, &msg, fd);
+}
+
+static void client_msg_notify(struct client_ring *r, uint32_t mask)
+{
+       struct udebug_client_msg msg = {
+               .type = CL_MSG_RING_NOTIFY,
+               .id = ring_id(r),
+               .notify_mask = mask,
+       };
+       struct client *cl;
+
+       list_for_each_entry(cl, &clients, list) {
+               if (cl->notify_id < 0 ||
+                   !(mask & (1 << cl->notify_id)))
+                       continue;
+
+               client_send_msg(cl, &msg, -1);
+       }
+}
+
+static void client_free(struct client *cl)
+{
+       struct client_ring *r;
+
+       while (!list_empty(&cl->bufs)) {
+               r = list_first_entry(&cl->bufs, struct client_ring, list);
+               client_ring_free(r);
+       }
+
+       DC(2, cl, "disconnect");
+       uloop_fd_delete(&cl->fd);
+       close(cl->fd.fd);
+       list_del(&cl->list);
+
+       free(cl);
+}
+
+static void client_parse_message(struct client *cl)
+{
+       struct udebug_client_msg *msg = &cl->rx_buf.msg;
+       struct client_ring *r;
+
+       DC(3, cl, "msg type=%d len=%d", msg->type, (unsigned int)cl->rx_ofs);
+       switch (msg->type) {
+       case CL_MSG_RING_ADD:
+               client_ring_alloc(cl);
+               break;
+       case CL_MSG_RING_REMOVE:
+               DC(2, cl, "delete ring %x", msg->id);
+               r = client_ring_get_by_id(cl, msg->id);
+               if (r)
+                       client_ring_free(r);
+               else
+                       DC(2, cl, "ring not found");
+               break;
+       case CL_MSG_RING_NOTIFY:
+               DC(3, cl, "notify on ring %d", msg->id);
+               r = client_ring_get_by_id(cl, msg->id);
+               if (r)
+                       client_msg_notify(r, msg->notify_mask);
+               else
+                       DC(2, cl, "local ring %d not found", msg->id);
+               break;
+       case CL_MSG_GET_HANDLE:
+               client_msg_get_handle(cl);
+               DC(2, cl, "get notify handle: %d", cl->notify_id);
+               break;
+       case CL_MSG_RING_GET:
+               DC(2, cl, "get ring %x", msg->id);
+               client_msg_ring_get(cl, msg->id);
+               break;
+       default:
+               DC(3, cl, "Invalid message type %d", msg->type);
+               break;
+       }
+}
+
+static void client_fd_cb(struct uloop_fd *fd, unsigned int events)
+{
+       struct client *cl = container_of(fd, struct client, fd);
+       uint8_t fd_buf[CMSG_SPACE(sizeof(int))] = {};
+       struct iovec iov = {};
+       struct msghdr msg = {
+               .msg_iov = &iov,
+               .msg_iovlen = 1,
+               .msg_control = fd_buf,
+               .msg_controllen = sizeof(fd_buf),
+       };
+       struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
+       size_t min_sz = sizeof(cl->rx_buf.msg) + sizeof(struct blob_attr);
+       ssize_t len;
+       int *pfd;
+
+       cmsg->cmsg_type = SCM_RIGHTS;
+       cmsg->cmsg_level = SOL_SOCKET;
+       cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+
+       pfd = (int *)CMSG_DATA(cmsg);
+       msg.msg_controllen = cmsg->cmsg_len;
+
+       if (fd->eof) {
+               client_free(cl);
+               return;
+       }
+
+retry:
+       iov.iov_base = &cl->rx_buf;
+       iov.iov_len = min_sz;
+       if (!cl->rx_ofs) {
+               iov.iov_base = &cl->rx_buf.msg;
+               iov.iov_len = min_sz;
+
+               len = recvmsg(fd->fd, &msg, 0);
+               if (len < 0)
+                       return;
+
+               cl->rx_ofs = len;
+               cl->rx_fd = *pfd;
+               goto retry;
+       } else if (cl->rx_ofs >= min_sz) {
+               iov.iov_len += blob_pad_len(&cl->rx_buf.data);
+               iov.iov_len -= sizeof(struct blob_attr);
+               if (iov.iov_len > sizeof(cl->rx_buf)) {
+                       client_free(cl);
+                       return;
+               }
+       }
+
+       iov.iov_base += cl->rx_ofs;
+       iov.iov_len -= cl->rx_ofs;
+       if (iov.iov_len) {
+               len = read(fd->fd, iov.iov_base, iov.iov_len);
+               if (len <= 0)
+                       return;
+
+               cl->rx_ofs += len;
+               goto retry;
+       }
+
+       client_parse_message(cl);
+       cl->rx_ofs = 0;
+       goto retry;
+}
+
+static void client_get_info(struct client *cl)
+{
+#ifdef LOCAL_PEERPID
+       socklen_t len = sizeof(&cl->pid);
+       if (getsockopt(cl->fd.fd, SOL_LOCAL, LOCAL_PEERPID, &cl->pid, &len) < 0)
+               return;
+#elif defined(SO_PEERCRED)
+       struct ucred uc;
+       socklen_t len = sizeof(uc);
+       if (getsockopt(cl->fd.fd, SOL_SOCKET, SO_PEERCRED, &uc, &len) < 0)
+               return;
+       cl->pid = uc.pid;
+       cl->uid = uc.uid;
+#endif
+}
+
+static void client_get_procname(struct client *cl)
+{
+#ifdef linux
+       char buf[256];
+       FILE *f;
+
+       snprintf(buf, sizeof(buf), "/proc/%d/cmdline", cl->pid);
+       f = fopen(buf, "r");
+       if (!f)
+               return;
+       buf[fread(buf, 1, sizeof(buf) - 1, f)] = 0;
+       fclose(f);
+       snprintf(cl->proc_name, sizeof(cl->proc_name), "%s", basename(buf));
+#endif
+#ifdef __APPLE__
+       proc_name(cl->pid, cl->proc_name, sizeof(cl->proc_name) - 1);
+#endif
+}
+
+void client_alloc(int fd)
+{
+       int sndbuf = UDEBUG_SNDBUF;
+       struct client *cl;
+
+       setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
+
+       cl = calloc(1, sizeof(*cl));
+       INIT_LIST_HEAD(&cl->bufs);
+       cl->fd.fd = fd;
+       cl->fd.cb = client_fd_cb;
+       cl->rx_fd = -1;
+       client_get_info(cl);
+       if (cl->pid)
+               client_get_procname(cl);
+       if (!cl->proc_name[0])
+               snprintf(cl->proc_name, sizeof(cl->proc_name), "<unknown>");
+
+       DC(2, cl, "connect");
+       uloop_fd_add(&cl->fd, ULOOP_READ);
+       list_add_tail(&cl->list, &clients);
+}
diff --git a/examples/test-source.c b/examples/test-source.c
new file mode 100644 (file)
index 0000000..cffcc8c
--- /dev/null
@@ -0,0 +1,36 @@
+#include <stdio.h>
+#include <libubox/utils.h>
+#include "udebug.h"
+
+static struct udebug ud;
+static struct udebug_buf udb;
+
+struct udebug_buf_flag buf_flags[] = {
+       { "enabled", 1ULL }
+};
+static const struct udebug_buf_meta buf_meta = {
+       .name = "counter",
+       .format = UDEBUG_FORMAT_STRING,
+       .flags = buf_flags,
+       .n_flags = ARRAY_SIZE(buf_flags),
+};
+
+int main(int argc, char **argv)
+{
+       int count = 0;
+
+       udebug_init(&ud);
+       udebug_connect(&ud, "./udebug.sock");
+
+       udebug_buf_init(&udb, 256, 128);
+       udebug_buf_add(&ud, &udb, &buf_meta);
+       while (1) {
+               udebug_entry_init(&udb);
+               udebug_entry_printf(&udb, "count=%d", count++);
+               udebug_entry_add(&udb);
+               if (count > 10000)
+                       sleep(1);
+       }
+
+       return 0;
+}
diff --git a/examples/test-source.uc b/examples/test-source.uc
new file mode 100755 (executable)
index 0000000..b04f6ee
--- /dev/null
@@ -0,0 +1,23 @@
+#!/usr/bin/env ucode
+let udebug = require("udebug");
+
+udebug.init("./udebug.sock");
+let buf = udebug.create_ring({
+       name: "counter",
+       size: 256,
+       entries: 128,
+});
+
+if (!buf) {
+       warn(`Failed to create buffer\n`);
+       exit(1);
+}
+
+let count = 0;
+signal('SIGINT', () => exit(0));
+signal('SIGTERM', () => exit(0));
+while (true) {
+       buf.add(`count=${count}`);
+       if (count++ > 1000)
+               sleep(1000);
+}
diff --git a/lib-pcap.c b/lib-pcap.c
new file mode 100644 (file)
index 0000000..63ca73f
--- /dev/null
@@ -0,0 +1,265 @@
+#include <stdio.h>
+#include <stdint.h>
+#include <string.h>
+#include <libubox/utils.h>
+#include <libubox/blobmsg.h>
+#include "udebug-pcap.h"
+#include "priv.h"
+
+static char pcap_buf[65536];
+static struct pcap_block_hdr *pcap_hdr = (struct pcap_block_hdr *)pcap_buf;
+
+struct pcap_block_hdr {
+       uint32_t type;
+       uint32_t len;
+};
+
+struct pcap_shb_hdr {
+       uint32_t endian;
+       uint16_t major;
+       uint16_t minor;
+       uint64_t section_len;
+};
+
+struct pcap_idb_hdr {
+       uint16_t link_type;
+       uint16_t _pad;
+       uint32_t snap_len;
+};
+
+struct pcap_epb_hdr {
+       uint32_t iface;
+       uint32_t ts_hi;
+       uint32_t ts_lo;
+       uint32_t cap_len;
+       uint32_t pkt_len;
+};
+
+struct pcap_opt_hdr {
+       uint16_t id;
+       uint16_t len;
+};
+
+#define PCAPNG_BTYPE_SHB       0x0a0d0d0a
+#define PCAPNG_BTYPE_IDB       1
+#define PCAPNG_BTYPE_EPB       6
+
+#define PCAPNG_ENDIAN          0x1a2b3c4d
+
+static void *
+pcap_block_start(uint32_t type, uint32_t len)
+{
+       struct pcap_block_hdr *b = pcap_hdr;
+
+       b->type = type;
+       b->len = len + sizeof(*b);
+       memset(b + 1, 0, len);
+
+       return b + 1;
+}
+
+static void *
+pcap_block_append(int len)
+{
+       struct pcap_block_hdr *b = pcap_hdr;
+       void *data = &pcap_buf[b->len];
+
+       memset(data, 0, len);
+       b->len += len;
+
+       return data;
+}
+
+static void *
+pcap_opt_append(int id, int len)
+{
+       struct pcap_opt_hdr *opt;
+
+       len = (len + 3) & ~3;
+       opt = pcap_block_append(sizeof(*opt) + len);
+       opt->id = id;
+       opt->len = len;
+
+       return opt + 1;
+}
+
+static void
+pcap_opt_str_add(int id, const char *val)
+{
+       int len;
+
+       if (!val)
+                return;
+
+       len = strlen(val) + 1;
+       memcpy(pcap_opt_append(id, len), val, len);
+}
+
+static void
+pcap_opt_u8_add(uint16_t id, uint8_t val)
+{
+       *(uint8_t *)pcap_opt_append(id, 1) = val;
+}
+
+static void
+pcap_opt_end(void)
+{
+       pcap_block_append(4);
+}
+
+static uint32_t __pcap_block_align(int offset, int val)
+{
+       struct pcap_block_hdr *b = pcap_hdr;
+       uint32_t cur_len = b->len - offset;
+       uint32_t aligned_len = (cur_len + (val - 1)) & ~(val - 1);
+       uint32_t pad = aligned_len - cur_len;
+
+       if (pad)
+               pcap_block_append(pad);
+
+       return pad;
+}
+
+static uint32_t pcap_block_align(int val)
+{
+       return __pcap_block_align(0, val);
+}
+
+static int
+pcap_block_end(void)
+{
+       struct pcap_block_hdr *b = (struct pcap_block_hdr *)pcap_buf;
+       uint32_t *len;
+
+       pcap_block_align(4);
+       len = (uint32_t *)&pcap_buf[b->len];
+       b->len += 4;
+       *len = b->len;
+
+       return *len;
+}
+
+
+int pcap_init(struct pcap_context *p, struct pcap_meta *meta)
+{
+       struct pcap_shb_hdr *shb;
+
+       shb = pcap_block_start(PCAPNG_BTYPE_SHB, sizeof(*shb));
+       shb->endian = PCAPNG_ENDIAN;
+       shb->major = 1;
+       shb->section_len = ~0ULL;
+       pcap_opt_str_add(2, meta->hw);
+       pcap_opt_str_add(3, meta->os);
+       pcap_opt_str_add(4, meta->app);
+       pcap_opt_end();
+       pcap_block_end();
+
+       return 0;
+}
+
+int pcap_interface_init(struct pcap_context *p, uint32_t *id,
+                       struct pcap_interface_meta *meta)
+{
+       struct pcap_idb_hdr *idb;
+
+       *id = p->iface_id++;
+       idb = pcap_block_start(PCAPNG_BTYPE_IDB, sizeof(*idb));
+       idb->link_type = meta->link_type;
+       idb->snap_len = 0xffff;
+       pcap_opt_str_add(2, meta->name);
+       pcap_opt_str_add(3, meta->description);
+       pcap_opt_u8_add(9, meta->time_res);
+       pcap_opt_end();
+       pcap_block_end();
+
+       return 0;
+}
+
+void pcap_packet_init(uint32_t iface, uint64_t ts)
+{
+       struct pcap_epb_hdr *epb;
+
+       epb = pcap_block_start(PCAPNG_BTYPE_EPB, sizeof(*epb));
+       epb->iface = iface;
+       epb->ts_hi = ts >> 32;
+       epb->ts_lo = (uint32_t)ts;
+}
+
+void *pcap_packet_append(const void *data, size_t len)
+{
+       void *buf;
+
+       buf = pcap_block_append(len);
+       if (data)
+               memcpy(buf, data, len);
+
+       return buf;
+}
+
+void pcap_packet_done(void)
+{
+       struct pcap_epb_hdr *epb = (struct pcap_epb_hdr *)&pcap_hdr[1];
+       unsigned int len;
+
+       len = pcap_hdr->len - sizeof(*pcap_hdr) - sizeof(*epb);
+       epb->cap_len = epb->pkt_len = len;
+       pcap_block_align(4);
+       pcap_block_end();
+}
+
+int pcap_interface_rbuf_init(struct pcap_context *p, struct udebug_remote_buf *rb)
+{
+       const struct udebug_packet_info *meta = rb->meta;
+       struct pcap_interface_meta if_meta = {
+               .time_res = 6,
+               .name = meta->attr[UDEBUG_META_IFACE_NAME],
+               .description = meta->attr[UDEBUG_META_IFACE_DESC],
+       };
+
+       if (rb->buf.hdr->format == UDEBUG_FORMAT_PACKET)
+               if_meta.link_type = rb->buf.hdr->sub_format;
+       else if (rb->buf.hdr->format == UDEBUG_FORMAT_STRING)
+               if_meta.link_type = 147;
+
+       return pcap_interface_init(p, &rb->pcap_iface, &if_meta);
+}
+
+int pcap_snapshot_packet_init(struct udebug *ctx, struct udebug_iter *it)
+{
+       struct udebug_remote_buf *rb;
+       struct udebug_snapshot *s = it->s;
+
+       rb = udebug_remote_buf_get(ctx, s->rbuf_idx);
+       if (!rb)
+               return -1;
+
+       pcap_packet_init(rb->pcap_iface, it->timestamp);
+
+       switch (s->format) {
+       case UDEBUG_FORMAT_PACKET:
+       case UDEBUG_FORMAT_STRING:
+               pcap_packet_append(it->data, it->len);
+               break;
+       case UDEBUG_FORMAT_BLOBMSG:
+               break;
+       default:
+               return -1;
+       }
+
+       pcap_packet_done();
+
+       return 0;
+}
+
+void pcap_block_write_file(FILE *f)
+{
+       fwrite(pcap_buf, pcap_hdr->len, 1, f);
+       fflush(f);
+}
+
+void *pcap_block_get(size_t *len)
+{
+       *len = pcap_hdr->len;
+
+       return pcap_buf;
+}
diff --git a/lib-remote.c b/lib-remote.c
new file mode 100644 (file)
index 0000000..f40b7f6
--- /dev/null
@@ -0,0 +1,365 @@
+#include "priv.h"
+
+static struct udebug_client_msg *
+send_and_wait(struct udebug *ctx, struct udebug_client_msg *msg, int *rfd)
+{
+       int type = msg->type;
+       int fd = -1;
+
+       udebug_send_msg(ctx, msg, NULL, -1);
+
+       do {
+               if (fd >= 0)
+                       close(fd);
+               fd = -1;
+               msg = __udebug_poll(ctx, &fd, true);
+       } while (msg && msg->type != type);
+       if (!msg)
+               return NULL;
+
+       if (rfd)
+               *rfd = fd;
+       else if (fd >= 0)
+               close(fd);
+
+       return msg;
+}
+
+static int
+udebug_remote_get_handle(struct udebug *ctx)
+{
+       struct udebug_client_msg *msg;
+       struct udebug_client_msg send_msg = {
+               .type = CL_MSG_GET_HANDLE,
+       };
+
+       if (ctx->poll_handle >= 0 || !udebug_is_connected(ctx))
+               return 0;
+
+       msg = send_and_wait(ctx, &send_msg, NULL);
+       if (!msg)
+               return -1;
+
+       ctx->poll_handle = msg->id;
+       return 0;
+}
+
+struct udebug_remote_buf *udebug_remote_buf_get(struct udebug *ctx, uint32_t id)
+{
+       struct udebug_remote_buf *rb;
+       void *key = (void *)(uintptr_t)id;
+
+       return avl_find_element(&ctx->remote_rings, key, rb, node);
+}
+
+int udebug_remote_buf_map(struct udebug *ctx, struct udebug_remote_buf *rb, uint32_t id)
+{
+       void *key = (void *)(uintptr_t)id;
+       struct udebug_client_msg *msg;
+       struct udebug_client_msg send_msg = {
+               .type = CL_MSG_RING_GET,
+               .id = id,
+       };
+       int fd = -1;
+
+       if (rb->buf.data || !udebug_is_connected(ctx))
+               return -1;
+
+       msg = send_and_wait(ctx, &send_msg, &fd);
+       if (!msg || fd < 0)
+               return -1;
+
+       if (udebug_buf_open(&rb->buf, fd, msg->ring_size, msg->data_size)) {
+               fprintf(stderr, "failed to open fd %d, ring_size=%d, data_size=%d\n", fd, msg->ring_size, msg->data_size);
+               close(fd);
+               return -1;
+       }
+
+       rb->pcap_iface = ~0;
+       rb->node.key = key;
+       avl_insert(&ctx->remote_rings, &rb->node);
+
+       return 0;
+}
+
+void udebug_remote_buf_unmap(struct udebug *ctx, struct udebug_remote_buf *rb)
+{
+       if (!rb->buf.data)
+               return;
+
+       avl_delete(&ctx->remote_rings, &rb->node);
+       udebug_buf_free(&rb->buf);
+       rb->poll = 0;
+       rb->node.key = NULL;
+       rb->pcap_iface = ~0;
+}
+
+int udebug_remote_buf_set_poll(struct udebug *ctx, struct udebug_remote_buf *rb, bool val)
+{
+       int handle;
+
+       if (!rb->buf.data)
+               return -1;
+
+       if (rb->poll == val)
+               return 0;
+
+       rb->poll = val;
+       if (!val)
+               return 0;
+
+       handle = udebug_remote_get_handle(ctx);
+       if (handle < 0)
+               return -1;
+
+       __atomic_fetch_or(&rb->buf.hdr->notify, 1UL << handle, __ATOMIC_RELAXED);
+       return 0;
+}
+
+static void
+rbuf_advance_read_head(struct udebug_remote_buf *rb, uint32_t head,
+                      uint32_t *data_start)
+{
+       struct udebug_hdr *hdr = rb->buf.hdr;
+       uint32_t min_head = head + 1 - rb->buf.ring_size;
+       uint32_t min_data = u32_get(&hdr->data_used) - rb->buf.data_size;
+       struct udebug_ptr *last_ptr = udebug_ring_ptr(hdr, head - 1);
+
+       if (!u32_get(&hdr->head_hi) && u32_sub(0, min_head) > 0)
+               min_head = 0;
+
+       /* advance head to skip over any entries that are guaranteed
+        * to be overwritten now. final check will be performed after
+        * data copying */
+
+       if (u32_sub(rb->head, min_head) < 0)
+               rb->head = min_head;
+
+       for (size_t i = 0; i < rb->buf.ring_size; i++) {
+               struct udebug_ptr *ptr = udebug_ring_ptr(hdr, rb->head);
+
+               if (data_start) {
+                       *data_start = u32_get(&ptr->start);
+                       __sync_synchronize();
+               }
+
+               if (ptr->timestamp > last_ptr->timestamp)
+                       continue;
+
+               if (u32_sub(ptr->start, min_data) > 0)
+                       break;
+
+               rb->head++;
+       }
+}
+
+void udebug_remote_buf_set_start_time(struct udebug_remote_buf *rb, uint64_t ts)
+{
+       struct udebug_hdr *hdr = rb->buf.hdr;
+       uint32_t head = u32_get(&hdr->head);
+       uint32_t start = rb->head, end = head;
+       uint32_t diff;
+
+       if (!hdr)
+               return;
+
+       rbuf_advance_read_head(rb, head, NULL);
+       while ((diff = u32_sub(end, start)) > 0) {
+               uint32_t cur = start + diff / 2;
+               struct udebug_ptr *ptr;
+
+               ptr = udebug_ring_ptr(hdr, cur);
+               if (ptr->timestamp > ts)
+                       end = cur - 1;
+               else
+                       start = cur + 1;
+       }
+
+       rb->head = start;
+}
+
+void udebug_remote_buf_set_start_offset(struct udebug_remote_buf *rb, uint32_t idx)
+{
+       if (!rb->buf.hdr)
+               return;
+
+       rb->head = rb->buf.hdr->head - idx;
+}
+
+void udebug_remote_buf_set_flags(struct udebug_remote_buf *rb, uint64_t mask, uint64_t set)
+{
+       struct udebug_hdr *hdr = rb->buf.hdr;
+
+       if (!hdr)
+               return;
+
+       if ((uintptr_t)mask)
+               __atomic_and_fetch(&hdr->flags[0], (uintptr_t)~mask, __ATOMIC_RELAXED);
+       if ((uintptr_t)set)
+               __atomic_or_fetch(&hdr->flags[0], (uintptr_t)set, __ATOMIC_RELAXED);
+
+       if (sizeof(mask) == sizeof(unsigned long))
+               return;
+
+       mask >>= 32;
+       if ((uintptr_t)mask)
+               __atomic_and_fetch(&hdr->flags[1], (uintptr_t)~mask, __ATOMIC_RELAXED);
+       if ((uintptr_t)set)
+               __atomic_or_fetch(&hdr->flags[1], (uintptr_t)set, __ATOMIC_RELAXED);
+}
+
+struct udebug_snapshot *
+udebug_remote_buf_snapshot(struct udebug_remote_buf *rb)
+{
+       struct udebug_hdr *hdr = rb->buf.hdr;
+       struct udebug_ptr *last_ptr;
+       uint32_t data_start, data_end, data_used;
+       struct udebug_snapshot *s = NULL;
+       struct udebug_ptr *ptr_buf, *first_ptr;
+       uint32_t data_size, ptr_size;
+       uint32_t head, first_idx;
+       uint32_t prev_read_head = rb->head;
+       void *data_buf;
+
+       if (!hdr)
+               return NULL;
+
+       head = u32_get(&hdr->head);
+       rbuf_advance_read_head(rb, head, &data_start);
+       if (rb->head == head)
+               return NULL;
+
+       first_idx = rb->head;
+       first_ptr = udebug_ring_ptr(hdr, first_idx);
+       last_ptr = udebug_ring_ptr(hdr, head - 1);
+       data_end = last_ptr->start + last_ptr->len;
+
+       data_size = data_end - data_start;
+       ptr_size = head - rb->head;
+       if (data_size > rb->buf.data_size || ptr_size > rb->buf.ring_size) {
+               fprintf(stderr, "Invalid data size: %x > %x, %x > %x\n", data_size, (int)rb->buf.data_size, ptr_size, (int)rb->buf.ring_size);
+               goto out;
+       }
+
+       s = calloc_a(sizeof(*s),
+                    &ptr_buf, ptr_size * sizeof(*ptr_buf),
+                    &data_buf, data_size);
+
+       s->data = memcpy(data_buf, udebug_buf_ptr(&rb->buf, data_start), data_size);
+       s->data_size = data_size;
+       s->entries = ptr_buf;
+       s->dropped = rb->head - prev_read_head;
+
+       if (first_ptr > last_ptr) {
+               struct udebug_ptr *start_ptr = udebug_ring_ptr(hdr, 0);
+               struct udebug_ptr *end_ptr = udebug_ring_ptr(hdr, rb->buf.ring_size - 1) + 1;
+               uint32_t size = end_ptr - first_ptr;
+               memcpy(s->entries, first_ptr, size * sizeof(*s->entries));
+               memcpy(s->entries + size, start_ptr, (last_ptr + 1 - start_ptr) * sizeof(*s->entries));
+       } else {
+               memcpy(s->entries, first_ptr, (last_ptr + 1 - first_ptr) * sizeof(*s->entries));
+       }
+
+       /* get a snapshot of the counter that indicates how much data has been
+        * clobbered by newly added entries */
+       __sync_synchronize();
+       data_used = u32_get(&hdr->data_used) - rb->buf.data_size;
+
+       s->n_entries = head - first_idx;
+
+       rbuf_advance_read_head(rb, head, NULL);
+       if (s->n_entries < rb->head - first_idx) {
+               free(s);
+               s = NULL;
+               goto out;
+       }
+
+       s->entries += rb->head - first_idx;
+       s->n_entries -= rb->head - first_idx;
+       while (s->n_entries > 0 &&
+              u32_sub(s->entries[0].start, data_used) < 0) {
+               s->entries++;
+               s->n_entries--;
+               s->dropped++;
+       }
+
+       for (size_t i = 0; i < s->n_entries; i++)
+               s->entries[i].start -= data_start;
+
+       s->format = hdr->format;
+       s->sub_format = hdr->sub_format;
+       s->rbuf_idx = (uint32_t)(uintptr_t)rb->node.key;
+
+out:
+       rb->head = head;
+       return s;
+}
+
+bool udebug_snapshot_get_entry(struct udebug_snapshot *s, struct udebug_iter *it, unsigned int entry)
+{
+       struct udebug_ptr *ptr;
+
+       it->len = 0;
+       if (entry >= s->n_entries)
+               goto error;
+
+       ptr = &s->entries[entry];
+       if (ptr->start > s->data_size || ptr->len > s->data_size ||
+           ptr->start + ptr->len > s->data_size)
+               goto error;
+
+       it->s = s;
+       it->data = s->data + ptr->start;
+       it->len = ptr->len;
+       it->timestamp = ptr->timestamp;
+       return true;
+
+error:
+       it->data = NULL;
+       return false;
+}
+
+void udebug_iter_start(struct udebug_iter *it, struct udebug_snapshot **s, size_t n)
+{
+       memset(it, 0, sizeof(*it));
+
+       it->list = s;
+       it->n = n;
+
+       for (size_t i = 0; i < it->n; i++)
+               it->list[i]->iter_idx = 0;
+}
+
+bool udebug_iter_next(struct udebug_iter *it)
+{
+       while (1) {
+               struct udebug_snapshot *s;
+               uint64_t cur_ts;
+               int cur = -1;
+
+               for (size_t i = 0; i < it->n; i++) {
+                       struct udebug_ptr *ptr;
+
+                       s = it->list[i];
+                       if (s->iter_idx >= s->n_entries)
+                               continue;
+
+                       ptr = &s->entries[s->iter_idx];
+                       if (cur >= 0 && ptr->timestamp > cur_ts)
+                               continue;
+
+                       cur = i;
+                       cur_ts = ptr->timestamp;
+               }
+
+               if (cur < 0)
+                       return false;
+
+               s = it->list[cur];
+               it->s_idx = cur;
+               if (!udebug_snapshot_get_entry(s, it, s->iter_idx++))
+                       continue;
+
+               return true;
+       }
+}
diff --git a/lib-ucode.c b/lib-ucode.c
new file mode 100644 (file)
index 0000000..932a39e
--- /dev/null
@@ -0,0 +1,649 @@
+#include <math.h>
+#include <libubox/utils.h>
+#include <libubox/usock.h>
+#include <ucode/module.h>
+#include "udebug.h"
+#include "udebug-pcap.h"
+
+static uc_resource_type_t *rbuf_type, *wbuf_type, *snapshot_type, *pcap_type;
+static uc_value_t *registry;
+static struct udebug u;
+static uc_vm_t *_vm;
+
+struct uc_pcap {
+       struct pcap_context pcap;
+       int fd;
+       FILE *f;
+};
+
+static size_t add_registry(uc_value_t *val)
+{
+       size_t i = 0;
+
+       while (ucv_array_get(registry, i))
+               i += 2;
+
+       ucv_array_set(registry, i, ucv_get(val));
+
+       return i;
+}
+
+static void
+uc_udebug_notify_cb(struct udebug *ctx, struct udebug_remote_buf *rb)
+{
+       uintptr_t idx = (uintptr_t)rb->priv;
+       uc_value_t *cb, *this;
+       uc_vm_t *vm = _vm;
+
+       this = ucv_array_get(registry, idx);
+       cb = ucv_array_get(registry, idx + 1);
+
+       if (!ucv_is_callable(cb))
+               return;
+
+       uc_vm_stack_push(vm, ucv_get(this));
+       uc_vm_stack_push(vm, ucv_get(cb));
+       if (uc_vm_call(vm, true, 0) != EXCEPTION_NONE)
+               return;
+
+       ucv_put(uc_vm_stack_pop(vm));
+}
+
+static uc_value_t *
+uc_udebug_init(uc_vm_t *vm, size_t nargs)
+{
+       uc_value_t *arg = uc_fn_arg(0);
+       uc_value_t *flag_auto = uc_fn_arg(1);
+       const char *path = NULL;
+
+       if (ucv_type(arg) == UC_STRING)
+               path = ucv_string_get(arg);
+
+       udebug_init(&u);
+       u.notify_cb = uc_udebug_notify_cb;
+       if (flag_auto && !ucv_is_truish(flag_auto)) {
+               if (udebug_connect(&u, path))
+                       return NULL;
+       } else {
+               udebug_auto_connect(&u, path);
+       }
+
+       return ucv_boolean_new(true);
+}
+
+static uc_value_t *
+uc_udebug_get_ring(uc_vm_t *vm, size_t nargs)
+{
+       struct udebug_remote_buf *rb;
+       struct udebug_packet_info *info;
+       uc_value_t *arg = uc_fn_arg(0);
+       uc_value_t *id, *proc, *name, *pid;
+       int ifname_len, ifdesc_len;
+       char *ifname_buf, *ifdesc_buf;
+       uc_value_t *res;
+       uintptr_t idx;
+
+#define R_IFACE_DESC   "%s:%d"
+
+       if (ucv_type(arg) != UC_OBJECT)
+               return NULL;
+
+       id = ucv_object_get(arg, "id", NULL);
+       proc = ucv_object_get(arg, "proc_name", NULL);
+       name = ucv_object_get(arg, "ring_name", NULL);
+       pid = ucv_object_get(arg, "pid", NULL);
+
+       if (ucv_type(id) != UC_INTEGER ||
+           ucv_type(proc) != UC_STRING ||
+           ucv_type(name) != UC_STRING ||
+           ucv_type(pid) != UC_INTEGER)
+               return NULL;
+
+       ifname_len = strlen(ucv_string_get(name)) + 1;
+       ifdesc_len = sizeof(R_IFACE_DESC) + strlen(ucv_string_get(proc)) + 10;
+       rb = calloc_a(sizeof(*rb),
+                     &info, sizeof(*info),
+                     &ifname_buf, ifname_len,
+                     &ifdesc_buf, ifdesc_len);
+       rb->meta = info;
+
+       strcpy(ifname_buf, ucv_string_get(name));
+       info->attr[UDEBUG_META_IFACE_NAME] = ifname_buf;
+       snprintf(ifdesc_buf, ifdesc_len, R_IFACE_DESC,
+                ucv_string_get(proc), (unsigned int)ucv_int64_get(pid));
+       info->attr[UDEBUG_META_IFACE_DESC] = ifdesc_buf;
+
+       if (udebug_remote_buf_map(&u, rb, (uint32_t)ucv_int64_get(id))) {
+               free(rb);
+               return NULL;
+       }
+
+       res = uc_resource_new(rbuf_type, rb);
+       idx = add_registry(res);
+       rb->priv = (void *)idx;
+
+       return res;
+}
+
+static void rbuf_free(void *ptr)
+{
+       struct udebug_remote_buf *rb = ptr;
+       uintptr_t idx;
+
+       if (!rb)
+               return;
+
+       idx = (uintptr_t)rb->priv;
+       ucv_array_set(registry, idx, NULL);
+       ucv_array_set(registry, idx + 1, NULL);
+       udebug_remote_buf_unmap(&u, rb);
+       free(rb);
+}
+
+static uc_value_t *
+uc_udebug_rbuf_fetch(uc_vm_t *vm, size_t nargs)
+{
+       struct udebug_remote_buf *rb = uc_fn_thisval("udebug.rbuf");
+       struct udebug_snapshot *s;
+
+       if (!rb)
+               return NULL;
+
+       s = udebug_remote_buf_snapshot(rb);
+       if (!s)
+               return NULL;
+
+       return uc_resource_new(snapshot_type, s);
+}
+
+static uc_value_t *
+uc_udebug_rbuf_set_poll_cb(uc_vm_t *vm, size_t nargs)
+{
+       struct udebug_remote_buf *rb = uc_fn_thisval("udebug.rbuf");
+       uc_value_t *val = uc_fn_arg(0);
+       uintptr_t idx;
+
+       if (!rb)
+               return NULL;
+
+       idx = (uintptr_t)rb->priv;
+       ucv_array_set(registry, idx + 1, ucv_get(val));
+       if (!u.fd.registered)
+               udebug_add_uloop(&u);
+       udebug_remote_buf_set_poll(&u, rb, ucv_is_callable(val));
+
+       return NULL;
+}
+
+static uc_value_t *
+uc_udebug_rbuf_set_fetch_duration(uc_vm_t *vm, size_t nargs)
+{
+       struct udebug_remote_buf *rb = uc_fn_thisval("udebug.rbuf");
+       uc_value_t *val = uc_fn_arg(0);
+       uint64_t ts;
+       double t;
+
+       if (!rb)
+               return NULL;
+
+       t = ucv_double_get(val);
+       if (isnan(t))
+               return NULL;
+
+       ts = udebug_timestamp();
+       ts -= (uint64_t)(fabs(t) * UDEBUG_TS_SEC);
+       udebug_remote_buf_set_start_time(rb, ts);
+
+       return ucv_boolean_new(true);
+}
+
+static uc_value_t *
+uc_udebug_rbuf_set_fetch_count(uc_vm_t *vm, size_t nargs)
+{
+       struct udebug_remote_buf *rb = uc_fn_thisval("udebug.rbuf");
+       uc_value_t *val = uc_fn_arg(0);
+       uint32_t count;
+
+       if (!rb)
+               return NULL;
+
+       count = ucv_int64_get(val);
+       udebug_remote_buf_set_start_offset(rb, count);
+
+       return ucv_boolean_new(true);
+}
+
+static uc_value_t *
+uc_udebug_rbuf_change_flags(uc_vm_t *vm, size_t nargs)
+{
+       struct udebug_remote_buf *rb = uc_fn_thisval("udebug.rbuf");
+       uc_value_t *mask = uc_fn_arg(0);
+       uc_value_t *set = uc_fn_arg(1);
+
+       if (!rb)
+               return NULL;
+
+       if (ucv_type(mask) != UC_INTEGER || ucv_type(set) != UC_INTEGER)
+               return NULL;
+
+       udebug_remote_buf_set_flags(rb, ucv_int64_get(mask), ucv_int64_get(set));
+       return ucv_boolean_new(true);
+}
+
+static uc_value_t *
+uc_udebug_rbuf_get_flags(uc_vm_t *vm, size_t nargs)
+{
+       struct udebug_remote_buf *rb = uc_fn_thisval("udebug.rbuf");
+       if (!rb)
+               return NULL;
+
+       return ucv_int64_new(udebug_buf_flags(&rb->buf));
+}
+
+static uc_value_t *
+uc_udebug_rbuf_close(uc_vm_t *vm, size_t nargs)
+{
+       void **p = uc_fn_this("udebug.rbuf");
+
+       if (!p)
+               return NULL;
+
+       rbuf_free(*p);
+       *p = NULL;
+
+       return NULL;
+}
+
+static void
+uc_udebug_pcap_init(struct uc_pcap *p, uc_value_t *args)
+{
+       uc_value_t *hw, *os, *app;
+       struct pcap_meta meta = {};
+
+       if (ucv_type(args) == UC_OBJECT) {
+               hw = ucv_object_get(args, "hw", NULL);
+               os = ucv_object_get(args, "os", NULL);
+               app = ucv_object_get(args, "app", NULL);
+
+               meta.hw = ucv_string_get(hw);
+               meta.os = ucv_string_get(os);
+               meta.app = ucv_string_get(app);
+       }
+
+       pcap_init(&p->pcap, &meta);
+}
+
+static void
+uc_udebug_pcap_write_block(struct uc_pcap *p)
+{
+       size_t len;
+       void *data;
+       int ret;
+
+       data = pcap_block_get(&len);
+       do {
+               ret = write(p->fd, data, len);
+       } while (ret < 0 && errno == EINTR);
+}
+
+static uc_value_t *
+uc_debug_pcap_init(int fd, uc_value_t *args)
+{
+       struct uc_pcap *p;
+
+       if (fd < 0)
+               return NULL;
+
+       p = calloc(1, sizeof(*p));
+       p->fd = fd;
+       uc_udebug_pcap_init(p, args);
+       uc_udebug_pcap_write_block(p);
+
+       return uc_resource_new(pcap_type, p);
+}
+
+static uc_value_t *
+uc_udebug_pcap_file(uc_vm_t *vm, size_t nargs)
+{
+       uc_value_t *file = uc_fn_arg(0);
+       uc_value_t *args = uc_fn_arg(1);
+       int fd = -1;
+
+       if (ucv_type(file) == UC_STRING)
+               fd = open(ucv_string_get(file), O_WRONLY | O_CREAT, 0644);
+       else if (!file)
+               fd = STDOUT_FILENO;
+
+       return uc_debug_pcap_init(fd, args);
+}
+
+static uc_value_t *
+uc_udebug_pcap_udp(uc_vm_t *vm, size_t nargs)
+{
+       uc_value_t *host = uc_fn_arg(0);
+       uc_value_t *port = uc_fn_arg(1);
+       uc_value_t *args = uc_fn_arg(2);
+       const char *port_str;
+       int fd = -1;
+
+       if (ucv_type(host) != UC_STRING)
+               return NULL;
+
+       if (ucv_type(port) == UC_STRING)
+               port_str = ucv_string_get(port);
+       else if (ucv_type(port) == UC_INTEGER)
+               port_str = usock_port(ucv_int64_get(port));
+       else
+               return NULL;
+
+       fd = usock(USOCK_UDP, ucv_string_get(host), port_str);
+
+       return uc_debug_pcap_init(fd, args);
+}
+
+static struct udebug_snapshot *
+uc_get_snapshot(uc_value_t *val)
+{
+       return ucv_resource_data(val, "udebug.snapshot");
+}
+
+static uc_value_t *
+uc_udebug_pcap_write(uc_vm_t *vm, size_t nargs)
+{
+       struct uc_pcap *p = uc_fn_thisval("udebug.pcap");
+       uc_value_t *arg = uc_fn_arg(0);
+       size_t n = ucv_type(arg) == UC_ARRAY ? ucv_array_length(arg) : 1;
+       struct udebug_snapshot **s;
+       struct udebug_iter it;
+
+       if (!p)
+               return NULL;
+
+       s = alloca(n * sizeof(*s));
+       if (ucv_type(arg) == UC_ARRAY)
+               for (size_t i = 0; i < n; i++) {
+                       if ((s[i] = uc_get_snapshot(ucv_array_get(arg, i))) == NULL)
+                               return NULL;
+       } else {
+               if ((s[0] = uc_get_snapshot(arg)) == NULL)
+                       return NULL;
+       }
+
+       udebug_iter_start(&it, s, n);
+       while (udebug_iter_next(&it)) {
+               struct udebug_remote_buf *rb;
+
+               rb = udebug_remote_buf_get(&u, it.s->rbuf_idx);
+               if (!pcap_interface_is_valid(&p->pcap, rb->pcap_iface)) {
+                       if (pcap_interface_rbuf_init(&p->pcap, rb))
+                               continue;
+
+                       uc_udebug_pcap_write_block(p);
+               }
+
+               if (pcap_snapshot_packet_init(&u, &it))
+                       continue;
+
+               uc_udebug_pcap_write_block(p);
+       }
+
+       return NULL;
+}
+
+static void
+uc_udebug_pcap_free(void *ptr)
+{
+       struct uc_pcap *p = ptr;
+
+       if (!p)
+               return;
+
+       if (p->fd >= 0)
+               close(p->fd);
+       free(p);
+}
+
+static uc_value_t *
+uc_udebug_pcap_close(uc_vm_t *vm, size_t nargs)
+{
+       void **p = uc_fn_this("udebug.pcap");
+
+       if (!p)
+               return NULL;
+
+       uc_udebug_pcap_free(*p);
+       *p = NULL;
+
+       return NULL;
+}
+
+static uc_value_t *
+uc_udebug_snapshot_get_ring(uc_vm_t *vm, size_t nargs)
+{
+       struct udebug_snapshot *s = uc_fn_thisval("udebug.snapshot");
+       struct udebug_remote_buf *rb;
+       uintptr_t idx;
+
+       if (!s)
+               return NULL;
+
+       rb = udebug_remote_buf_get(&u, s->rbuf_idx);
+       if (!rb)
+               return NULL;
+
+       idx = (uintptr_t)rb->priv;
+       return ucv_array_get(registry, idx);
+}
+
+static uc_value_t *
+uc_udebug_foreach_packet(uc_vm_t *vm, size_t nargs)
+{
+       uc_value_t *arg = uc_fn_arg(0);
+       uc_value_t *fn = uc_fn_arg(1);
+       size_t n = ucv_type(arg) == UC_ARRAY ? ucv_array_length(arg) : 1;
+       struct udebug_snapshot **s;
+       struct udebug_iter it;
+
+       if (!ucv_is_callable(fn))
+               return NULL;
+
+       s = alloca(n * sizeof(*s));
+       if (ucv_type(arg) == UC_ARRAY)
+               for (size_t i = 0; i < n; i++) {
+                       if ((s[i] = uc_get_snapshot(ucv_array_get(arg, i))) == NULL)
+                               return NULL;
+       } else {
+               if ((s[0] = uc_get_snapshot(arg)) == NULL)
+                       return NULL;
+       }
+
+       udebug_iter_start(&it, s, n);
+       while (udebug_iter_next(&it)) {
+               uc_value_t *s_obj;
+
+               if (ucv_type(arg) == UC_ARRAY)
+                       s_obj = ucv_array_get(arg, it.s_idx);
+               else
+                       s_obj = arg;
+
+               uc_vm_stack_push(vm, ucv_get(_uc_fn_this_res(vm)));
+               uc_vm_stack_push(vm, ucv_get(fn));
+               uc_vm_stack_push(vm, ucv_get(s_obj));
+               uc_vm_stack_push(vm, ucv_string_new_length(it.data, it.len));
+
+               if (uc_vm_call(vm, true, 2) != EXCEPTION_NONE)
+                       break;
+
+               ucv_put(uc_vm_stack_pop(vm));
+       }
+
+       return NULL;
+}
+
+static uc_value_t *
+uc_udebug_create_ring(uc_vm_t *vm, size_t nargs)
+{
+       uc_value_t *name, *flags_arr, *size, *entries;
+       uc_value_t *meta_obj = uc_fn_arg(0);
+       struct udebug_buf_flag *flags;
+       struct udebug_buf_meta *meta;
+       struct udebug_buf *buf;
+       size_t flag_str_len = 0;
+       size_t flags_len = 0;
+       char *name_buf, *flag_name_buf;
+
+       if (ucv_type(meta_obj) != UC_OBJECT)
+               return NULL;
+
+       name = ucv_object_get(meta_obj, "name", NULL);
+       flags_arr = ucv_object_get(meta_obj, "flags", NULL);
+       size = ucv_object_get(meta_obj, "size", NULL);
+       entries = ucv_object_get(meta_obj, "entries", NULL);
+
+       if (ucv_type(name) != UC_STRING ||
+           ucv_type(size) != UC_INTEGER || ucv_type(entries) != UC_INTEGER)
+               return NULL;
+
+       if (ucv_type(flags_arr) == UC_ARRAY) {
+               flags_len = ucv_array_length(flags_arr);
+               for (size_t i = 0; i < flags_len; i++) {
+                       uc_value_t *f = ucv_array_get(flags_arr, i);
+                       if (ucv_type(f) != UC_STRING)
+                               return NULL;
+                       flag_str_len += strlen(ucv_string_get(f)) + 1;
+               }
+       }
+
+       buf = calloc_a(sizeof(*buf),
+                      &name_buf, strlen(ucv_string_get(name)) + 1,
+                      &meta, sizeof(meta),
+                      &flags, flags_len * sizeof(*flags),
+                      &flag_name_buf, flag_str_len);
+       meta->name = strcpy(name_buf, ucv_string_get(name));
+       meta->format = UDEBUG_FORMAT_STRING;
+       meta->flags = flags;
+
+       for (size_t i = 0; i < flags_len; i++) {
+               uc_value_t *f = ucv_array_get(flags_arr, i);
+               const char *str = ucv_string_get(f);
+               size_t len = strlen(str) + 1;
+
+               flags->name = memcpy(name_buf, str, len);
+               flags->mask = 1ULL << i;
+               name_buf += len;
+               meta->n_flags++;
+       }
+
+       if (udebug_buf_init(buf, ucv_int64_get(size), ucv_int64_get(entries))) {
+               free(buf);
+               return NULL;
+       }
+
+       udebug_buf_add(&u, buf, meta);
+
+       return uc_resource_new(wbuf_type, buf);
+}
+
+static void wbuf_free(void *ptr)
+{
+       if (!ptr)
+               return;
+
+       udebug_buf_free(ptr);
+       free(ptr);
+}
+
+static uc_value_t *
+uc_udebug_wbuf_flags(uc_vm_t *vm, size_t nargs)
+{
+       struct udebug_buf *buf = uc_fn_thisval("udebug.wbuf");
+
+       if (!buf)
+               return NULL;
+
+       return ucv_int64_new(udebug_buf_flags(buf));
+}
+
+static uc_value_t *
+uc_udebug_wbuf_close(uc_vm_t *vm, size_t nargs)
+{
+       void **p = uc_fn_this("udebug.wbuf");
+
+       if (!p)
+               return NULL;
+
+       wbuf_free(*p);
+       *p = NULL;
+
+       return NULL;
+}
+
+static void
+uc_udebug_wbuf_add_string(struct udebug_buf *buf, uc_value_t *val)
+{
+       udebug_entry_init(buf);
+       udebug_entry_append(buf, ucv_string_get(val), ucv_string_length(val));
+       udebug_entry_add(buf);
+}
+
+static uc_value_t *
+uc_udebug_wbuf_add(uc_vm_t *vm, size_t nargs)
+{
+       struct udebug_buf *buf = uc_fn_thisval("udebug.wbuf");
+       uc_value_t *arg = uc_fn_arg(0);
+
+       if (!buf || ucv_type(arg) != UC_STRING)
+               return NULL;
+
+       uc_udebug_wbuf_add_string(buf, arg);
+
+       return ucv_boolean_new(true);
+}
+
+static const uc_function_list_t pcap_fns[] = {
+       { "close", uc_udebug_pcap_close },
+       { "write", uc_udebug_pcap_write },
+};
+
+static const uc_function_list_t snapshot_fns[] = {
+       { "get_ring", uc_udebug_snapshot_get_ring }
+};
+
+static const uc_function_list_t wbuf_fns[] = {
+       { "add", uc_udebug_wbuf_add },
+       { "flags", uc_udebug_wbuf_flags },
+       { "close", uc_udebug_wbuf_close },
+};
+
+static const uc_function_list_t rbuf_fns[] = {
+       { "set_poll_cb", uc_udebug_rbuf_set_poll_cb },
+       { "fetch", uc_udebug_rbuf_fetch },
+       { "change_flags", uc_udebug_rbuf_change_flags },
+       { "get_flags", uc_udebug_rbuf_get_flags },
+       { "set_fetch_duration", uc_udebug_rbuf_set_fetch_duration },
+       { "set_fetch_count", uc_udebug_rbuf_set_fetch_count },
+       { "close", uc_udebug_rbuf_close },
+};
+
+static const uc_function_list_t global_fns[] = {
+       { "init", uc_udebug_init },
+       { "create_ring", uc_udebug_create_ring },
+       { "get_ring", uc_udebug_get_ring },
+       { "pcap_file", uc_udebug_pcap_file },
+       { "pcap_udp", uc_udebug_pcap_udp },
+       { "foreach_packet", uc_udebug_foreach_packet },
+};
+
+void uc_module_init(uc_vm_t *vm, uc_value_t *scope)
+{
+       _vm = vm;
+       uc_function_list_register(scope, global_fns);
+
+       wbuf_type = uc_type_declare(vm, "udebug.wbuf", wbuf_fns, wbuf_free);
+       rbuf_type = uc_type_declare(vm, "udebug.rbuf", rbuf_fns, rbuf_free);
+       snapshot_type = uc_type_declare(vm, "udebug.snapshot", snapshot_fns, free);
+       pcap_type = uc_type_declare(vm, "udebug.pcap", pcap_fns, uc_udebug_pcap_free);
+
+       registry = ucv_array_new(vm);
+       uc_vm_registry_set(vm, "udebug.registry", registry);
+}
diff --git a/lib.c b/lib.c
new file mode 100644 (file)
index 0000000..7be36bb
--- /dev/null
+++ b/lib.c
@@ -0,0 +1,737 @@
+#define _GNU_SOURCE
+#include <sys/types.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <unistd.h>
+#include <string.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <poll.h>
+#include <time.h>
+#include "priv.h"
+
+#include <libubox/usock.h>
+
+#define ALIGN(i, sz)   (((i) + (sz) - 1) & ~((sz) - 1))
+
+#ifndef MAP_ANONYMOUS
+#define MAP_ANONYMOUS MAP_ANON
+#endif
+
+#define UDEBUG_MIN_ALLOC_LEN   128
+static struct blob_buf b;
+
+static void __randname(char *template)
+{
+       int i;
+       struct timespec ts;
+       unsigned long r;
+
+       clock_gettime(CLOCK_REALTIME, &ts);
+       r = ts.tv_sec + ts.tv_nsec;
+       for (i=0; i<6; i++, r>>=5)
+               template[i] = 'A'+(r&15)+(r&16)*2;
+}
+
+int udebug_id_cmp(const void *k1, const void *k2, void *ptr)
+{
+       uint32_t id1 = (uint32_t)(uintptr_t)k1, id2 = (uint32_t)(uintptr_t)k2;
+       return id1 - id2;
+}
+
+static inline int
+shm_open_anon(char *name)
+{
+       char *template = name + strlen(name) - 6;
+       int fd;
+
+       if (template < name || memcmp(template, "XXXXXX", 6) != 0)
+               return -1;
+
+       for (int i = 0; i < 100; i++) {
+               __randname(template);
+               fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600);
+               if (fd >= 0) {
+                       if (shm_unlink(name) < 0) {
+                               close(fd);
+                               continue;
+                       }
+                       return fd;
+               }
+
+               if (fd < 0 && errno != EEXIST)
+                       return -1;
+       }
+
+       return -1;
+}
+
+uint64_t udebug_timestamp(void)
+{
+       struct timespec ts;
+       uint64_t val;
+
+       clock_gettime(CLOCK_REALTIME, &ts);
+
+       val = ts.tv_sec;
+       val *= UDEBUG_TS_SEC;
+       val += ts.tv_nsec / 1000;
+
+       return val;
+}
+
+static int
+__udebug_buf_map(struct udebug_buf *buf)
+{
+       void *ptr, *ptr2;
+
+       ptr = mmap(NULL, buf->head_size + 2 * buf->data_size, PROT_NONE,
+                  MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+       if (ptr == MAP_FAILED)
+               return -1;
+
+       ptr2 = mmap(ptr, buf->head_size + buf->data_size,
+                   PROT_READ | PROT_WRITE, MAP_FIXED | MAP_SHARED, buf->fd, 0);
+       if (ptr2 != ptr)
+               goto err_unmap;
+
+       ptr2 = mmap(ptr + buf->head_size + buf->data_size, buf->data_size,
+                   PROT_READ | PROT_WRITE, MAP_FIXED | MAP_SHARED, buf->fd,
+                   buf->head_size);
+       if (ptr2 != ptr + buf->head_size + buf->data_size)
+               goto err_unmap;
+
+       buf->hdr = ptr;
+       buf->data = ptr + buf->head_size;
+       return 0;
+
+err_unmap:
+       munmap(ptr, buf->head_size + 2 * buf->data_size);
+       return -1;
+}
+
+static int
+writev_retry(int fd, struct iovec *iov, int iov_len, int sock_fd)
+{
+       uint8_t fd_buf[CMSG_SPACE(sizeof(int))] = { 0 };
+       struct msghdr msghdr = { 0 };
+       struct cmsghdr *cmsg;
+       int len = 0;
+       int *pfd;
+
+       msghdr.msg_iov = iov,
+       msghdr.msg_iovlen = iov_len,
+       msghdr.msg_control = fd_buf;
+       msghdr.msg_controllen = sizeof(fd_buf);
+
+       cmsg = CMSG_FIRSTHDR(&msghdr);
+       cmsg->cmsg_type = SCM_RIGHTS;
+       cmsg->cmsg_level = SOL_SOCKET;
+       cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+
+       pfd = (int *) CMSG_DATA(cmsg);
+       msghdr.msg_controllen = cmsg->cmsg_len;
+
+       do {
+               ssize_t cur_len;
+
+               if (sock_fd < 0) {
+                       msghdr.msg_control = NULL;
+                       msghdr.msg_controllen = 0;
+               } else {
+                       *pfd = sock_fd;
+               }
+
+               cur_len = sendmsg(fd, &msghdr, 0);
+               if (cur_len < 0) {
+                       struct pollfd pfd = {
+                               .fd = fd,
+                               .events = POLLOUT
+                       };
+
+                       switch(errno) {
+                       case EAGAIN:
+                               poll(&pfd, 1, -1);
+                               break;
+                       case EINTR:
+                               break;
+                       default:
+                               return -1;
+                       }
+                       continue;
+               }
+
+               if (len > 0)
+                       sock_fd = -1;
+
+               len += cur_len;
+               while (cur_len >= (ssize_t) iov->iov_len) {
+                       cur_len -= iov->iov_len;
+                       iov_len--;
+                       iov++;
+                       if (!iov_len)
+                               return len;
+               }
+               iov->iov_base += cur_len;
+               iov->iov_len -= cur_len;
+               msghdr.msg_iov = iov;
+               msghdr.msg_iovlen = iov_len;
+       } while (1);
+
+       /* Should never reach here */
+       return -1;
+}
+
+static int
+recv_retry(int fd, struct iovec *iov, bool wait, int *recv_fd)
+{
+       uint8_t fd_buf[CMSG_SPACE(sizeof(int))] = { 0 };
+       struct msghdr msghdr = { 0 };
+       struct cmsghdr *cmsg;
+       int total = 0;
+       int bytes;
+       int *pfd;
+
+       msghdr.msg_iov = iov,
+       msghdr.msg_iovlen = 1,
+       msghdr.msg_control = fd_buf;
+       msghdr.msg_controllen = sizeof(fd_buf);
+
+       cmsg = CMSG_FIRSTHDR(&msghdr);
+       cmsg->cmsg_type = SCM_RIGHTS;
+       cmsg->cmsg_level = SOL_SOCKET;
+       cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+
+       pfd = (int *) CMSG_DATA(cmsg);
+
+       while (iov->iov_len > 0) {
+               if (recv_fd) {
+                       msghdr.msg_control = fd_buf;
+                       msghdr.msg_controllen = cmsg->cmsg_len;
+               } else {
+                       msghdr.msg_control = NULL;
+                       msghdr.msg_controllen = 0;
+               }
+
+               *pfd = -1;
+               bytes = recvmsg(fd, &msghdr, 0);
+               if (!bytes)
+                       return -2;
+               if (bytes < 0) {
+                       bytes = 0;
+                       if (errno == EINTR)
+                               continue;
+
+                       if (errno != EAGAIN)
+                               return -2;
+               }
+               if (!wait && !bytes)
+                       return 0;
+
+               if (recv_fd)
+                       *recv_fd = *pfd;
+               else if (*pfd >= 0)
+                       close(*pfd);
+
+               if (bytes > 0)
+                       recv_fd = NULL;
+
+               wait = true;
+               iov->iov_len -= bytes;
+               iov->iov_base += bytes;
+               total += bytes;
+
+               if (iov->iov_len > 0) {
+                       struct pollfd pfd = {
+                               .fd = fd,
+                               .events = POLLIN
+                       };
+                       int ret;
+                       do {
+                               ret = poll(&pfd, 1, UDEBUG_TIMEOUT);
+                       } while (ret < 0 && errno == EINTR);
+
+                       if (!(pfd.revents & POLLIN))
+                               return -1;
+               }
+       }
+
+       return total;
+}
+
+void udebug_send_msg(struct udebug *ctx, struct udebug_client_msg *msg,
+                    struct blob_attr *meta, int fd)
+{
+       struct iovec iov[2] = {
+               { .iov_base = msg, .iov_len = sizeof(*msg) },
+               {}
+       };
+
+       if (!meta) {
+               blob_buf_init(&b, 0);
+               meta = b.head;
+       }
+
+       iov[1].iov_base = meta;
+       iov[1].iov_len = blob_pad_len(meta);
+       writev_retry(ctx->fd.fd, iov, ARRAY_SIZE(iov), fd);
+}
+
+static void
+udebug_buf_msg(struct udebug_buf *buf, enum udebug_client_msg_type type)
+{
+       struct udebug_client_msg msg = {
+               .type = type,
+               .id = buf->id,
+       };
+
+       udebug_send_msg(buf->ctx, &msg, NULL, -1);
+}
+
+static size_t __udebug_headsize(unsigned int ring_size, unsigned int page_size)
+{
+       ring_size *= sizeof(struct udebug_ptr);
+       return ALIGN(sizeof(struct udebug_hdr) + ring_size, page_size);
+}
+
+int udebug_buf_open(struct udebug_buf *buf, int fd, uint32_t ring_size, uint32_t data_size)
+{
+       INIT_LIST_HEAD(&buf->list);
+       buf->fd = fd;
+       buf->ring_size = ring_size;
+       buf->head_size = __udebug_headsize(ring_size, sysconf(_SC_PAGESIZE));
+       buf->data_size = data_size;
+
+       if (buf->ring_size > (1U << 24) || buf->data_size > (1U << 29))
+               return -1;
+
+       if (__udebug_buf_map(buf))
+               return -1;
+
+       if (buf->ring_size != buf->hdr->ring_size ||
+               buf->data_size != buf->hdr->data_size) {
+               munmap(buf->hdr, buf->head_size + 2 * buf->data_size);
+               buf->hdr = NULL;
+               return -1;
+       }
+
+       return 0;
+}
+
+int udebug_buf_init(struct udebug_buf *buf, size_t entries, size_t size)
+{
+       uint32_t pagesz = sysconf(_SC_PAGESIZE);
+       char filename[] = "/udebug.XXXXXX";
+       unsigned int order = 12;
+       uint8_t ring_order = 5;
+       size_t head_size;
+       int fd;
+
+       INIT_LIST_HEAD(&buf->list);
+       if (size < pagesz)
+               size = pagesz;
+       while(size > 1 << order)
+               order++;
+       size = 1 << order;
+       while (entries > 1 << ring_order)
+               ring_order++;
+       entries = 1 << ring_order;
+
+       if (size > (1U << 29) || entries > (1U << 24))
+               return -1;
+
+       head_size = __udebug_headsize(entries, pagesz);
+       while (ALIGN(sizeof(*buf->hdr) + (entries * 2) * sizeof(struct udebug_ptr), pagesz) == head_size)
+               entries *= 2;
+
+       fd = shm_open_anon(filename);
+       if (fd < 0)
+               return -1;
+
+       if (ftruncate(fd, head_size + size) < 0)
+               goto err_close;
+
+       buf->head_size = head_size;
+       buf->data_size = size;
+       buf->ring_size = entries;
+       buf->fd = fd;
+
+       if (__udebug_buf_map(buf))
+               goto err_close;
+
+       buf->hdr->ring_size = entries;
+       buf->hdr->data_size = size;
+
+       /* ensure hdr changes are visible */
+       __sync_synchronize();
+
+       return 0;
+
+err_close:
+       close(fd);
+       return -1;
+}
+
+static void *udebug_buf_alloc(struct udebug_buf *buf, uint32_t ofs, uint32_t len)
+{
+       struct udebug_hdr *hdr = buf->hdr;
+
+       hdr->data_used = u32_max(hdr->data_used, ofs + len + 1);
+
+       /* ensure that data_used update is visible before clobbering data */
+       __sync_synchronize();
+
+       return udebug_buf_ptr(buf, ofs);
+}
+
+uint64_t udebug_buf_flags(struct udebug_buf *buf)
+{
+       struct udebug_hdr *hdr = buf->hdr;
+       uint64_t flags;
+
+       if (!hdr)
+               return 0;
+
+       flags = hdr->flags[0];
+       if (sizeof(flags) != sizeof(uintptr_t))
+               flags |= ((uint64_t)hdr->flags[1]) << 32;
+
+       return flags;
+}
+
+void udebug_entry_init_ts(struct udebug_buf *buf, uint64_t timestamp)
+{
+       struct udebug_hdr *hdr = buf->hdr;
+       struct udebug_ptr *ptr;
+
+       if (!hdr)
+               return;
+
+       ptr = udebug_ring_ptr(hdr, hdr->head);
+       ptr->start = hdr->data_head;
+       ptr->len = 0;
+       ptr->timestamp = timestamp;
+}
+
+void *udebug_entry_append(struct udebug_buf *buf, const void *data, uint32_t len)
+{
+       struct udebug_hdr *hdr = buf->hdr;
+       struct udebug_ptr *ptr;
+       uint32_t ofs;
+       void *ret;
+
+       if (!hdr)
+               return NULL;
+
+       ptr = udebug_ring_ptr(hdr, hdr->head);
+       ofs = ptr->start + ptr->len;
+       if (ptr->len + len > buf->data_size / 2)
+               return NULL;
+
+       ret = udebug_buf_alloc(buf, ofs, len);
+       if (data)
+               memcpy(ret, data, len);
+       ptr->len += len;
+
+       return ret;
+}
+
+int udebug_entry_printf(struct udebug_buf *buf, const char *fmt, ...)
+{
+       va_list ap;
+       size_t ret;
+
+       va_start(ap, fmt);
+       ret = udebug_entry_vprintf(buf, fmt, ap);
+       va_end(ap);
+
+       return ret;
+}
+
+int udebug_entry_vprintf(struct udebug_buf *buf, const char *fmt, va_list ap)
+{
+       struct udebug_hdr *hdr = buf->hdr;
+       struct udebug_ptr *ptr;
+       uint32_t ofs;
+       uint32_t len;
+       char *str;
+
+       if (!hdr)
+               return -1;
+
+       ptr = udebug_ring_ptr(hdr, hdr->head);
+       ofs = ptr->start + ptr->len;
+       if (ptr->len > buf->data_size / 2)
+               return -1;
+
+       str = udebug_buf_alloc(buf, ofs, UDEBUG_MIN_ALLOC_LEN);
+       len = vsnprintf(str, UDEBUG_MIN_ALLOC_LEN, fmt, ap);
+       if (len <= UDEBUG_MIN_ALLOC_LEN)
+               goto out;
+
+       if (ptr->len + len > buf->data_size / 2)
+               return -1;
+
+       udebug_buf_alloc(buf, ofs, len + 1);
+       len = vsnprintf(str, len, fmt, ap);
+
+out:
+       ptr->len += len;
+       return 0;
+}
+
+void udebug_entry_add(struct udebug_buf *buf)
+{
+       struct udebug_hdr *hdr = buf->hdr;
+       struct udebug_ptr *ptr = udebug_ring_ptr(hdr, hdr->head);
+       uint32_t notify;
+       uint8_t *data;
+
+       /* ensure strings are always 0-terminated */
+       data = udebug_buf_ptr(buf, ptr->start + ptr->len);
+       *data = 0;
+       hdr->data_head = ptr->start + ptr->len + 1;
+
+       /* ensure that all data changes are visible before advancing head */
+       __sync_synchronize();
+
+       u32_set(&hdr->head, u32_get(&hdr->head) + 1);
+       if (!u32_get(&hdr->head))
+               u32_set(&hdr->head_hi, u32_get(&hdr->head_hi) + 1);
+
+       /* ensure that head change is visible */
+       __sync_synchronize();
+
+       notify = __atomic_exchange_n(&hdr->notify, 0, __ATOMIC_RELAXED);
+       if (notify) {
+               struct udebug_client_msg msg = {
+                       .type = CL_MSG_RING_NOTIFY,
+                       .id = buf->id,
+                       .notify_mask = notify,
+               };
+               blob_buf_init(&b, 0);
+
+               udebug_send_msg(buf->ctx, &msg, b.head, -1);
+       }
+}
+void udebug_buf_free(struct udebug_buf *buf)
+{
+       struct udebug *ctx = buf->ctx;
+
+       if (!list_empty(&buf->list) && buf->list.prev)
+               list_del(&buf->list);
+
+       if (ctx && ctx->fd.fd >= 0)
+               udebug_buf_msg(buf, CL_MSG_RING_REMOVE);
+
+       munmap(buf->hdr, buf->head_size + buf->data_size);
+       close(buf->fd);
+       memset(buf, 0, sizeof(*buf));
+}
+
+static void
+__udebug_buf_add(struct udebug *ctx, struct udebug_buf *buf)
+{
+       struct udebug_client_msg msg = {
+               .type = CL_MSG_RING_ADD,
+               .id = buf->id,
+               .ring_size = buf->hdr->ring_size,
+               .data_size = buf->hdr->data_size,
+       };
+       const struct udebug_buf_meta *meta = buf->meta;
+       void *c;
+
+       blob_buf_init(&b, 0);
+       blobmsg_add_string(&b, "name", meta->name);
+       c = blobmsg_open_array(&b, "flags");
+       for (size_t i = 0; i < meta->n_flags; i++) {
+               const struct udebug_buf_flag *flag = &meta->flags[i];
+               void *e = blobmsg_open_array(&b, NULL);
+               blobmsg_add_string(&b, NULL, flag->name);
+               blobmsg_add_u64(&b, NULL, flag->mask);
+               blobmsg_close_array(&b, e);
+       }
+       blobmsg_close_array(&b, c);
+
+       udebug_send_msg(ctx, &msg, b.head, buf->fd);
+}
+
+int udebug_buf_add(struct udebug *ctx, struct udebug_buf *buf,
+                  const struct udebug_buf_meta *meta)
+{
+       list_add_tail(&buf->list, &ctx->local_rings);
+       buf->ctx = ctx;
+       buf->meta = meta;
+       buf->id = ctx->next_id++;
+       buf->hdr->format = meta->format;
+       buf->hdr->sub_format = meta->sub_format;
+
+       if (ctx->fd.fd >= 0)
+               __udebug_buf_add(ctx, buf);
+
+       return 0;
+}
+
+void udebug_init(struct udebug *ctx)
+{
+       INIT_LIST_HEAD(&ctx->local_rings);
+       avl_init(&ctx->remote_rings, udebug_id_cmp, true, NULL);
+       ctx->fd.fd = -1;
+       ctx->poll_handle = -1;
+}
+
+static void udebug_reconnect_cb(struct uloop_timeout *t)
+{
+       struct udebug *ctx = container_of(t, struct udebug, reconnect);
+
+       if (udebug_connect(ctx, ctx->socket_path) < 0) {
+               uloop_timeout_set(&ctx->reconnect, 1000);
+               return;
+       }
+
+       udebug_add_uloop(ctx);
+}
+
+void udebug_auto_connect(struct udebug *ctx, const char *path)
+{
+       free(ctx->socket_path);
+       ctx->reconnect.cb = udebug_reconnect_cb;
+       ctx->socket_path = path ? strdup(path) : NULL;
+       if (ctx->fd.fd >= 0)
+               return;
+
+       udebug_reconnect_cb(&ctx->reconnect);
+}
+
+int udebug_connect(struct udebug *ctx, const char *path)
+{
+       struct udebug_remote_buf *rb;
+       struct udebug_buf *buf;
+
+       if (ctx->fd.fd >= 0)
+               close(ctx->fd.fd);
+       ctx->fd.fd = -1;
+
+       if (!path)
+               path = UDEBUG_SOCK_NAME;
+
+       ctx->fd.fd = usock(USOCK_UNIX, path, NULL);
+       if (ctx->fd.fd < 0)
+               return -1;
+
+       list_for_each_entry(buf, &ctx->local_rings, list)
+               __udebug_buf_add(ctx, buf);
+
+       avl_for_each_element(&ctx->remote_rings, rb, node) {
+               if (!rb->poll)
+                       continue;
+
+               rb->poll = false;
+               udebug_remote_buf_set_poll(ctx, rb, true);
+       }
+
+       return 0;
+}
+
+static bool
+udebug_recv_msg(struct udebug *ctx, struct udebug_client_msg *msg, int *fd,
+               bool wait)
+{
+       struct iovec iov = {
+               .iov_base = msg,
+               .iov_len = sizeof(*msg)
+       };
+       int ret;
+
+       ret = recv_retry(ctx->fd.fd, &iov, wait, fd);
+       if (ret == -2)
+               uloop_fd_delete(&ctx->fd);
+
+       return ret == sizeof(*msg);
+}
+
+struct udebug_client_msg *__udebug_poll(struct udebug *ctx, int *fd, bool wait)
+{
+       static struct udebug_client_msg msg = {};
+
+       while (udebug_recv_msg(ctx, &msg, fd, wait)) {
+               struct udebug_remote_buf *rb;
+               void *key;
+
+               if (msg.type != CL_MSG_RING_NOTIFY)
+                       return &msg;
+
+               if (fd && *fd >= 0)
+                       close(*fd);
+
+               if (!ctx->notify_cb)
+                       continue;
+
+               key = (void *)(uintptr_t)msg.id;
+               rb = avl_find_element(&ctx->remote_rings, key, rb, node);
+               if (!rb || !rb->poll)
+                       continue;
+
+               if (ctx->poll_handle >= 0)
+                       __atomic_fetch_or(&rb->buf.hdr->notify,
+                                         1UL << ctx->poll_handle,
+                                         __ATOMIC_RELAXED);
+               ctx->notify_cb(ctx, rb);
+       }
+
+       return NULL;
+}
+
+void udebug_poll(struct udebug *ctx)
+{
+       while (__udebug_poll(ctx, NULL, false));
+}
+
+static void udebug_fd_cb(struct uloop_fd *fd, unsigned int events)
+{
+       struct udebug *ctx = container_of(fd, struct udebug, fd);
+
+       if (fd->eof)
+               uloop_fd_delete(fd);
+
+       udebug_poll(ctx);
+}
+
+void udebug_add_uloop(struct udebug *ctx)
+{
+       if (ctx->fd.registered)
+               return;
+
+       ctx->fd.cb = udebug_fd_cb;
+       uloop_fd_add(&ctx->fd, ULOOP_READ);
+}
+
+void __udebug_disconnect(struct udebug *ctx, bool reconnect)
+{
+       uloop_fd_delete(&ctx->fd);
+       close(ctx->fd.fd);
+       ctx->fd.fd = -1;
+       ctx->poll_handle = -1;
+       if (ctx->reconnect.cb)
+               uloop_timeout_set(&ctx->reconnect, 1);
+}
+
+void udebug_free(struct udebug *ctx)
+{
+       struct udebug_remote_buf *rb, *tmp;
+       struct udebug_buf *buf;
+
+       free(ctx->socket_path);
+       ctx->socket_path = NULL;
+
+       __udebug_disconnect(ctx, false);
+
+       while (!list_empty(&ctx->local_rings)) {
+               buf = list_first_entry(&ctx->local_rings, struct udebug_buf, list);
+               udebug_buf_free(buf);
+       }
+
+       avl_for_each_element_safe(&ctx->remote_rings, rb, node, tmp)
+               udebug_remote_buf_unmap(ctx, rb);
+}
diff --git a/main.c b/main.c
new file mode 100644 (file)
index 0000000..4a11963
--- /dev/null
+++ b/main.c
@@ -0,0 +1,96 @@
+#include <sys/stat.h>
+#include <sys/socket.h>
+#include <getopt.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <errno.h>
+
+#include <libubox/usock.h>
+
+#include "server.h"
+
+static struct uloop_fd server_fd;
+static char *socket_name;
+int debug_level = 3;
+
+static void server_fd_cb(struct uloop_fd *ufd, unsigned int events)
+{
+       D(3, "cb");
+       while (1) {
+               int fd = accept(ufd->fd, NULL, 0);
+               if (fd < 0) {
+                       if (errno == EINTR || errno == ECONNABORTED)
+                               continue;
+                       return;
+               }
+
+               client_alloc(fd);
+       }
+}
+
+static int usage(const char *progname)
+{
+       fprintf(stderr, "Usage: %s [options]\n"
+               "Options:\n"
+               "       -s <name>:              Set path to socket\n"
+               "\n", progname);
+       return 1;
+}
+
+static void mkdir_sockdir(void)
+{
+       char *sep;
+
+       sep = strrchr(socket_name, '/');
+       if (!sep)
+               return;
+
+       *sep = 0;
+       mkdir(socket_name, 0755);
+       *sep = '/';
+}
+
+int main(int argc, char **argv)
+{
+       int ret = -1;
+       int ch;
+
+       while ((ch = getopt(argc, argv, "s:")) != -1) {
+               switch (ch) {
+               case 's':
+                       socket_name = optarg;
+                       break;
+               default:
+                       return usage(argv[0]);
+               }
+       }
+
+       if (!socket_name)
+               socket_name = strdup(UDEBUG_SOCK_NAME);
+
+       signal(SIGPIPE, SIG_IGN);
+
+       uloop_init();
+
+       unlink(socket_name);
+       mkdir_sockdir();
+       umask(0111);
+       server_fd.cb = server_fd_cb;
+       server_fd.fd = usock(USOCK_UNIX | USOCK_SERVER | USOCK_NONBLOCK, socket_name, NULL);
+       if (server_fd.fd < 0) {
+               perror("usock");
+               goto out;
+       }
+
+       uloop_fd_add(&server_fd, ULOOP_READ);
+       udebug_ubus_init();
+       uloop_run();
+
+out:
+       udebug_ubus_free();
+       unlink(socket_name);
+       uloop_done();
+
+       return ret;
+}
diff --git a/priv.h b/priv.h
new file mode 100644 (file)
index 0000000..54000f1
--- /dev/null
+++ b/priv.h
@@ -0,0 +1,87 @@
+#ifndef __UDEBUG_UTIL_H
+#define __UDEBUG_UTIL_H
+
+#include <libubox/blobmsg.h>
+#include "udebug.h"
+
+#define UDEBUG_TIMEOUT 1000
+
+struct udebug_hdr {
+       uint32_t ring_size;
+       uint32_t data_size;
+
+       uint32_t format;
+       uint32_t sub_format;
+
+       uintptr_t flags[8 / sizeof(uintptr_t)];
+       uintptr_t notify;
+
+       uint32_t head_hi;
+       uint32_t head;
+       uint32_t data_head;
+       uint32_t data_used;
+};
+
+enum udebug_client_msg_type {
+       CL_MSG_RING_ADD,
+       CL_MSG_RING_REMOVE,
+       CL_MSG_RING_NOTIFY,
+       CL_MSG_GET_HANDLE,
+       CL_MSG_RING_GET,
+       CL_MSG_ERROR,
+};
+
+struct udebug_client_msg {
+       uint8_t type;
+       uint8_t _pad[3];
+       uint32_t id;
+       union {
+               struct {
+                       uint32_t ring_size, data_size;
+               };
+               uint32_t notify_mask;
+       };
+} __attribute__((packed, aligned(4)));
+
+static inline struct udebug_ptr *
+udebug_ring_ptr(struct udebug_hdr *hdr, uint32_t idx)
+{
+       struct udebug_ptr *ring = (struct udebug_ptr *)&hdr[1];
+       return &ring[idx & (hdr->ring_size - 1)];
+}
+
+static inline void *udebug_buf_ptr(struct udebug_buf *buf, uint32_t ofs)
+{
+       return buf->data + (ofs & (buf->data_size - 1));
+}
+
+int udebug_id_cmp(const void *k1, const void *k2, void *ptr);
+__hidden int udebug_buf_open(struct udebug_buf *buf, int fd, uint32_t ring_size, uint32_t data_size);
+__hidden struct udebug_client_msg *__udebug_poll(struct udebug *ctx, int *fd, bool wait);
+__hidden void udebug_send_msg(struct udebug *ctx, struct udebug_client_msg *msg,
+                    struct blob_attr *meta, int fd);
+__hidden void __udebug_disconnect(struct udebug *ctx, bool reconnect);
+
+static inline int32_t u32_sub(uint32_t a, uint32_t b)
+{
+       return a - b;
+}
+
+static inline int32_t u32_max(uint32_t a, uint32_t b)
+{
+       return u32_sub(a, b) > 0 ? a : b;
+}
+
+static inline void u32_set(void *ptr, uint32_t val)
+{
+       volatile uint32_t *v = ptr;
+       *v = val;
+}
+
+static inline uint32_t u32_get(void *ptr)
+{
+       volatile uint32_t *v = ptr;
+       return *v;
+}
+
+#endif
diff --git a/ring.c b/ring.c
new file mode 100644 (file)
index 0000000..7c869f5
--- /dev/null
+++ b/ring.c
@@ -0,0 +1,85 @@
+#include "server.h"
+
+static FILE *urandom;
+
+AVL_TREE(rings, udebug_id_cmp, true, NULL);
+
+struct client_ring *client_ring_get_by_id(struct client *cl, uint32_t id)
+{
+       struct client_ring *r;
+
+       list_for_each_entry(r, &cl->bufs, list)
+               if (r->id == id)
+                       return r;
+
+       return NULL;
+}
+
+static uint32_t gen_ring_id(void)
+{
+       uint32_t val = 0;
+
+       if (!urandom && (urandom = fopen("/dev/urandom", "r")) == NULL)
+               return 0;
+
+       fread(&val, sizeof(val), 1, urandom);
+
+       return val;
+}
+
+struct client_ring *client_ring_alloc(struct client *cl)
+{
+       enum {
+               RING_ATTR_NAME,
+               RING_ATTR_FLAGS,
+               __RING_ATTR_MAX,
+       };
+       static const struct blobmsg_policy policy[__RING_ATTR_MAX] = {
+               [RING_ATTR_NAME] = { "name", BLOBMSG_TYPE_STRING },
+               [RING_ATTR_FLAGS] = { "flags", BLOBMSG_TYPE_ARRAY },
+       };
+       struct udebug_client_msg *msg = &cl->rx_buf.msg;
+       struct blob_attr *tb[__RING_ATTR_MAX], *meta;
+       struct client_ring *r;
+       size_t meta_len;
+
+       if (cl->rx_fd < 0)
+               return NULL;
+
+       meta_len = blob_pad_len(&cl->rx_buf.data);
+       r = calloc_a(sizeof(*r), &meta, meta_len);
+       memcpy(meta, cl->rx_buf.buf, meta_len);
+
+       blobmsg_parse_attr(policy, __RING_ATTR_MAX, tb, meta);
+       if (!tb[RING_ATTR_NAME]) {
+               close(cl->rx_fd);
+               free(r);
+               return NULL;
+       }
+
+       r->name = blobmsg_get_string(tb[RING_ATTR_NAME]);
+       r->flags = tb[RING_ATTR_FLAGS];
+
+       r->cl = cl;
+       r->id = msg->id;
+       r->fd = cl->rx_fd;
+       r->ring_size = msg->ring_size;
+       r->data_size = msg->data_size;
+       list_add_tail(&r->list, &cl->bufs);
+
+       r->node.key = (void *)(uintptr_t)gen_ring_id();
+       avl_insert(&rings, &r->node);
+       udebug_ubus_ring_notify(r, true);
+       DC(2, cl, "add ring %d [%x] ring_size=%x data_size=%x", r->id, ring_id(r), r->ring_size, r->data_size);
+
+       return r;
+}
+
+void client_ring_free(struct client_ring *r)
+{
+       DC(2, r->cl, "free ring %d [%x]", r->id, ring_id(r));
+       udebug_ubus_ring_notify(r, false);
+       avl_delete(&rings, &r->node);
+       list_del(&r->list);
+       free(r);
+}
diff --git a/server.h b/server.h
new file mode 100644 (file)
index 0000000..ba581b7
--- /dev/null
+++ b/server.h
@@ -0,0 +1,78 @@
+#ifndef __UDEBUG_SERVER_H
+#define __UDEBUG_SERVER_H
+
+#include <libubox/list.h>
+#include <libubox/uloop.h>
+#include <libubox/avl.h>
+#include "priv.h"
+
+extern int debug_level;
+
+#define D(level, format, ...)                                                  \
+       do {                                                                    \
+               if (debug_level >= level)                                       \
+                       fprintf(stderr, "DEBUG: %s(%d) " format "\n",           \
+                               __func__, __LINE__, ##__VA_ARGS__);             \
+       } while (0)
+
+#define DC(level, cl, format, ...)                                             \
+       D(level, "[%s(%d)] " format, cl->proc_name, cl->pid, ##__VA_ARGS__)
+
+struct client {
+       struct list_head list;
+       struct list_head bufs;
+       struct uloop_fd fd;
+       int notify_id;
+
+       char proc_name[64];
+       int pid;
+       int uid;
+
+       int rx_fd;
+       size_t rx_ofs;
+       struct {
+               struct udebug_client_msg msg;
+               union {
+                       struct blob_attr data;
+                       uint8_t buf[4096];
+               };
+       } __attribute__((packed,aligned(4))) rx_buf;
+};
+
+struct client_ring {
+       struct list_head list;
+       struct avl_node node;
+       struct client *cl;
+
+       int fd;
+       uint32_t id;
+       uint32_t ring_size, data_size;
+       const char *name;
+       struct blob_attr *flags;
+};
+
+extern struct avl_tree rings;
+
+void client_alloc(int fd);
+struct client_ring *client_ring_alloc(struct client *cl);
+struct client_ring *client_ring_get_by_id(struct client *cl, uint32_t id);
+void client_ring_free(struct client_ring *r);
+
+static inline uint32_t ring_id(struct client_ring *r)
+{
+       return (uint32_t)(uintptr_t)r->node.key;
+}
+
+static inline struct client_ring *ring_get_by_id(uint32_t id)
+{
+       struct client_ring *r;
+       void *key = (void *)(uintptr_t)id;
+
+       return avl_find_element(&rings, key, r, node);
+}
+
+void udebug_ubus_init(void);
+void udebug_ubus_ring_notify(struct client_ring *r, bool add);
+void udebug_ubus_free(void);
+
+#endif
diff --git a/ubus.c b/ubus.c
new file mode 100644 (file)
index 0000000..a58ccb3
--- /dev/null
+++ b/ubus.c
@@ -0,0 +1,152 @@
+#include <fnmatch.h>
+#include <libubus.h>
+#include "server.h"
+
+struct ubus_auto_conn conn;
+struct blob_buf b;
+static struct ubus_object udebug_object;
+
+enum {
+       LIST_ATTR_PROCNAME,
+       LIST_ATTR_RINGNAME,
+       LIST_ATTR_PID,
+       LIST_ATTR_UID,
+       __LIST_ATTR_MAX,
+};
+
+static const struct blobmsg_policy list_policy[__LIST_ATTR_MAX] = {
+       [LIST_ATTR_PROCNAME] = { "proc_name", BLOBMSG_TYPE_ARRAY },
+       [LIST_ATTR_RINGNAME] = { "ring_name", BLOBMSG_TYPE_ARRAY },
+       [LIST_ATTR_PID] = { "pid", BLOBMSG_TYPE_ARRAY },
+       [LIST_ATTR_UID] = { "uid", BLOBMSG_TYPE_ARRAY },
+};
+
+static bool
+string_array_match(const char *val, struct blob_attr *match)
+{
+       struct blob_attr *cur;
+       int rem;
+
+       if (!match || !blobmsg_len(match))
+               return true;
+
+       if (blobmsg_check_array(match, BLOBMSG_TYPE_STRING) < 0)
+               return false;
+
+       blobmsg_for_each_attr(cur, match, rem) {
+               if (fnmatch(blobmsg_get_string(cur), val, 0) == 0)
+                       return true;
+       }
+
+       return false;
+}
+
+static bool
+int_array_match(unsigned int val, struct blob_attr *match)
+{
+       struct blob_attr *cur;
+       int rem;
+
+       if (!match || !blobmsg_len(match))
+               return true;
+
+       if (blobmsg_check_array(match, BLOBMSG_TYPE_INT32) < 0)
+               return false;
+
+       blobmsg_for_each_attr(cur, match, rem) {
+               if (val == blobmsg_get_u32(cur))
+                       return true;
+       }
+
+       return false;
+}
+
+static bool
+udebug_list_match(struct client_ring *r, struct blob_attr **tb)
+{
+       return string_array_match(r->cl->proc_name, tb[LIST_ATTR_PROCNAME]) &&
+              string_array_match(r->name, tb[LIST_ATTR_RINGNAME]) &&
+              int_array_match(r->cl->pid, tb[LIST_ATTR_PID]) &&
+              int_array_match(r->cl->uid, tb[LIST_ATTR_UID]);
+}
+
+static void
+udebug_list_add_ring_data(struct client_ring *r)
+{
+       blobmsg_add_u32(&b, "id", ring_id(r));
+       blobmsg_add_string(&b, "proc_name", r->cl->proc_name);
+       blobmsg_add_string(&b, "ring_name", r->name);
+       blobmsg_add_u32(&b, "pid", r->cl->pid);
+       blobmsg_add_u32(&b, "uid", r->cl->uid);
+       if (r->flags)
+               blobmsg_add_blob(&b, r->flags);
+}
+
+void udebug_ubus_ring_notify(struct client_ring *r, bool add)
+{
+       blob_buf_init(&b, 0);
+       udebug_list_add_ring_data(r);
+       ubus_notify(&conn.ctx, &udebug_object, add ? "add" : "remove", b.head, -1);
+}
+
+static void
+udebug_list_add_ring(struct client_ring *r)
+{
+       void *c;
+
+       c = blobmsg_open_table(&b, NULL);
+       udebug_list_add_ring_data(r);
+       blobmsg_close_table(&b, c);
+}
+
+static int
+udebug_list(struct ubus_context *ctx, struct ubus_object *obj,
+           struct ubus_request_data *req, const char *method,
+           struct blob_attr *msg)
+{
+       struct blob_attr *tb[__LIST_ATTR_MAX];
+       struct client_ring *r;
+       void *c;
+
+       blobmsg_parse_attr(list_policy, __LIST_ATTR_MAX, tb, msg);
+
+       blob_buf_init(&b, 0);
+       c = blobmsg_open_array(&b, "results");
+       avl_for_each_element(&rings, r, node)
+               if (udebug_list_match(r, tb))
+                       udebug_list_add_ring(r);
+       blobmsg_close_array(&b, c);
+       ubus_send_reply(ctx, req, b.head);
+
+       return 0;
+}
+
+static const struct ubus_method udebug_methods[] = {
+       UBUS_METHOD("list", udebug_list, list_policy),
+};
+
+static struct ubus_object_type udebug_object_type =
+       UBUS_OBJECT_TYPE("udebug", udebug_methods);
+
+static struct ubus_object udebug_object = {
+       .name = "udebug",
+       .type = &udebug_object_type,
+       .methods = udebug_methods,
+       .n_methods = ARRAY_SIZE(udebug_methods),
+};
+
+static void ubus_connect_cb(struct ubus_context *ctx)
+{
+       ubus_add_object(ctx, &udebug_object);
+}
+
+void udebug_ubus_init(void)
+{
+       conn.cb = ubus_connect_cb;
+       ubus_auto_connect(&conn);
+}
+
+void udebug_ubus_free(void)
+{
+       ubus_auto_shutdown(&conn);
+}
diff --git a/udebug-cli b/udebug-cli
new file mode 100755 (executable)
index 0000000..6d0b98b
--- /dev/null
@@ -0,0 +1,279 @@
+#!/usr/bin/env ucode
+'use strict';
+import { basename } from "fs";
+let udebug = require("udebug");
+let uloop = require("uloop");
+let libubus = require("ubus");
+uloop.init();
+let ubus = libubus.connect();
+
+let opts = {
+       select: []
+};
+
+const usage_message = `
+Usage: ${basename(sourcepath())} [<options>] <command> [<args>]
+
+  Options:
+    -f                         Ignore errors on opening rings
+    -d <duration>:             Only fetch data up to <duration> seconds old
+    -o <file>|-                        Set output file for snapshot/stream (or '-' for stdout)
+    -i <process>[:<name>]      Select debug buffer for snapshot/stream
+    -s <path>                  Use udebug socket <path>
+    -q                         Suppress warnings/error messages
+
+  Commands:
+    list:                      List available debug buffers
+    snapshot:                  Create a pcapng snapshot of debug buffers
+    set_flag [<name>=0|1 ...]  Set ring buffer flags
+    get_flags                  Get ring buffer flags
+
+`;
+
+function _warn(str) {
+       if (opts.quiet)
+               return;
+
+       warn(str);
+}
+
+function usage() {
+       warn(usage_message);
+       exit(1);
+}
+
+while (substr(ARGV[0], 0, 1) == "-") {
+       let opt = substr(shift(ARGV), 1);
+       switch(opt) {
+       case 'd':
+               opts.duration = 1.0 * shift(ARGV);
+               break;
+       case 's':
+               opts.socket = shift(ARGV);
+               break;
+       case 'i':
+               push(opts.select, shift(ARGV));
+               break;
+       case 'o':
+               opts.output_file = shift(ARGV);
+               break;
+       case 'q':
+               opts.quiet = true;
+               break;
+       case 'f':
+               opts.force = true;
+               break;
+       default:
+               usage();
+       }
+}
+
+let procs = {};
+let selected = [];
+let rings = {};
+let subscriber;
+let pcap;
+
+function ring_selected(ring) {
+       if (!length(opts.select))
+               return true;
+
+       for (let sel in opts.select) {
+               let match = split(sel, ":", 2);
+               if (wildcard(ring.proc_name, match[0]) &&
+                   (!match[1] || wildcard(ring.ring_name, match[1])))
+                       return true;
+       }
+
+       return false;
+}
+
+function poll_data() {
+       let data = [];
+       for (let ring_id in rings) {
+               let ring = rings[ring_id];
+               let s = ring[1].fetch();
+               if (s)
+                       push(data, s);
+       }
+       if (length(data) > 0)
+               pcap.write(data);
+}
+
+function open_ring(ring, poll) {
+       let ring_name =` ${ring.proc_name}:${ring.ring_name}`;
+       let ref = udebug.get_ring(ring);
+
+       if (!ref)
+               return null;
+       if (opts.duration)
+               ref.set_fetch_duration(opts.duration);
+       if (poll)
+               ref.set_poll_cb(() => { poll_data() });
+
+       let ring_id = ring.id + "";
+       ring = [ ring_name, ref ];
+       rings[ring_id] = ring;
+
+       return ring;
+}
+
+function open_output() {
+       if (!opts.output_file) {
+               _warn(`No output file\n`);
+               exit(1);
+       }
+       let out = opts.output_file;
+       if (out == "-")
+               out = null;
+
+       pcap = udebug.pcap_file(out);
+       if (!pcap) {
+               _warn(`Failed to open output\n`);
+               exit(1);
+       }
+}
+
+let cmds = {
+       list: function() {
+               for (let proc in procs) {
+                   print(`Process ${proc}:\n`);
+                   for (let ring in procs[proc])
+                       print(`  - ${ring.ring_name}\n`);
+               }
+       },
+       snapshot: function() {
+               open_output();
+
+               if (!length(selected)) {
+                       _warn(`No available debug buffers\n`);
+                       exit(1);
+               }
+
+               for (let ring in selected) {
+                       if (!open_ring(ring)) {
+                               _warn(`Failed to open ring ${ring_name}\n`);
+                               if (opts.force)
+                                       continue;
+
+                               exit(1);
+                       }
+               }
+
+               poll_data();
+               pcap.close();
+       },
+       set_flag: function() {
+               for (let ring in selected) {
+                       if (!length(ring.flags))
+                               continue;
+
+                       let mask = 0, set = 0;
+                       for (let flag in ring.flags) {
+                               for (let change in ARGV) {
+                                       change = split(change, "=", 2);
+                                       let name = change[0];
+                                       let val = !!int(change[1]);
+                                       if (flag[0] == name)
+                                               if (val)
+                                                       set |= flag[1];
+                                               else
+                                                       mask |= flag[1];
+                               }
+                       }
+
+                       if (!(mask | set))
+                               continue;
+
+                       let r = open_ring(ring);
+                       if (!r)
+                               continue;
+
+                       r[1].change_flags(mask, set);
+               }
+       },
+       get_flags: function() {
+               for (let ring in selected) {
+                       if (!length(ring.flags))
+                               continue;
+
+                       let r = open_ring(ring);
+                       if (!r)
+                               continue;
+
+                       print(`${r[0]}\n`);
+                       let flags = r[1].get_flags();
+                       for (let flag in ring.flags)
+                               print(`\t${flag[0]}=${((flags & flag[1]) == flag[1]) ? 1 : 0 }\n`);
+               }
+       },
+       stream: function() {
+               open_output();
+
+               subscriber = ubus.subscriber((req) => {
+                       let type = req.type;
+                       let ring = req.data;
+                       let ring_id = ring.id + "";
+                       if (type == "remove") {
+                               ring = rings[ring_id];
+                               if (!ring)
+                                       return;
+
+                               ring[1].close();
+                               delete rings[ring_id];
+                       } else if (type == "add") {
+                               open_ring(ring, true);
+                               poll_data();
+                       }
+               });
+               subscriber.subscribe("udebug");
+               for (let ring in selected) {
+                       if (!open_ring(ring, true)) {
+                               _warn(`Failed to open ring ${ring_name}\n`);
+                               if (opts.force)
+                                       continue;
+
+                               exit(1);
+                       }
+               }
+
+               let done = () => { uloop.done(); };
+               signal('SIGINT', done);
+               signal('SIGTERM', done);
+
+               poll_data();
+               delete opts.duration;
+               uloop.run();
+       }
+};
+
+let cmd = shift(ARGV);
+if (!cmds[cmd])
+       usage();
+
+let ring_list = ubus.call("udebug", "list");
+if (!ring_list || !ring_list.results) {
+       warn("Failed to get ring buffer list from udebugd\n");
+       exit(1);
+}
+
+ring_list = ring_list.results;
+for (let ring in ring_list) {
+       if (!ring_selected(ring))
+               continue;
+
+       let proc = procs[ring.proc_name];
+       if (!proc) {
+           proc = [];
+           procs[ring.proc_name] = proc;
+       }
+       push(proc, ring);
+       push(selected, ring);
+}
+
+if (cmd != "list" && !udebug.init(opts.socket)) {
+       _warn(`Failed to connect to udebug socket\n`);
+       exit(1);
+}
+
+cmds[cmd]();
diff --git a/udebug-pcap.h b/udebug-pcap.h
new file mode 100644 (file)
index 0000000..0faef87
--- /dev/null
@@ -0,0 +1,49 @@
+#ifndef __UDEBUG_PCAP_H
+#define __UDEBUG_PCAP_H
+
+#include <libubox/blobmsg.h>
+#include "udebug.h"
+
+struct pcap_context {
+       uint32_t iface_id;
+       void *buf;
+};
+
+struct pcap_meta {
+       const char *hw, *os, *app;
+};
+
+struct pcap_interface_meta {
+       const char *name;
+       const char *description;
+       uint8_t time_res;
+       uint16_t link_type;
+};
+
+struct pcap_dbus_meta {
+       const char *path, *interface, *name;
+       const char *src, *dest;
+};
+
+int pcap_init(struct pcap_context *p, struct pcap_meta *meta);
+int pcap_interface_init(struct pcap_context *p, uint32_t *id,
+                       struct pcap_interface_meta *meta);
+static inline bool
+pcap_interface_is_valid(struct pcap_context *p, uint32_t idx)
+{
+       return idx <= p->iface_id;
+}
+
+void pcap_packet_init(uint32_t iface, uint64_t timestamp);
+void pcap_dbus_init_string(const struct udebug_packet_info *meta, const char *val);
+void pcap_dbus_init_blob(const struct udebug_packet_info *meta, struct blob_attr *val, bool dict);
+void *pcap_packet_append(const void *data, size_t len);
+void pcap_packet_done(void);
+
+int pcap_interface_rbuf_init(struct pcap_context *p, struct udebug_remote_buf *rb);
+int pcap_snapshot_packet_init(struct udebug *ctx, struct udebug_iter *it);
+
+void pcap_block_write_file(FILE *f);
+void *pcap_block_get(size_t *len);
+
+#endif
diff --git a/udebug.h b/udebug.h
new file mode 100644 (file)
index 0000000..51f10c9
--- /dev/null
+++ b/udebug.h
@@ -0,0 +1,176 @@
+#ifndef __UDEBUG_RINGBUF_H
+#define __UDEBUG_RINGBUF_H
+
+#include <sys/types.h>
+#include <stdint.h>
+#include <stdarg.h>
+
+#include <libubox/list.h>
+#include <libubox/uloop.h>
+#include <libubox/avl.h>
+
+#define UDEBUG_SOCK_NAME       "/var/run/udebug.sock"
+
+enum udebug_format {
+       UDEBUG_FORMAT_PACKET,
+       UDEBUG_FORMAT_STRING,
+       UDEBUG_FORMAT_BLOBMSG,
+};
+
+enum {
+       UDEBUG_DLT_ETHERNET = 1,
+       UDEBUG_DLT_PPP = 50,
+       UDEBUG_DLT_RAW_IP = 101,
+       UDEBUG_DLT_IEEE_802_11 = 105,
+       UDEBUG_DLT_IEEE_802_11_RADIOTAP = 127,
+       UDEBUG_DLT_NETLINK = 253,
+};
+
+enum udebug_meta_type {
+       UDEBUG_META_IFACE_NAME,
+       UDEBUG_META_IFACE_DESC,
+       __UDEBUG_META_MAX
+};
+
+#define UDEBUG_TS_MSEC  1000ULL
+#define UDEBUG_TS_SEC  (1000ULL * UDEBUG_TS_MSEC)
+
+struct udebug;
+struct udebug_hdr;
+
+struct udebug_buf_flag {
+       const char *name;
+       uint64_t mask;
+};
+
+struct udebug_buf_meta {
+       const char *name;
+       enum udebug_format format;
+       uint32_t sub_format; /* linktype for UDEBUG_FORMAT_PACKET */
+       const struct udebug_buf_flag *flags;
+       unsigned int n_flags;
+};
+
+struct udebug_buf {
+       struct udebug *ctx;
+       const struct udebug_buf_meta *meta;
+       uint32_t id;
+
+       struct list_head list;
+
+       struct udebug_hdr *hdr;
+       void *data;
+       size_t data_size;
+       size_t head_size;
+       size_t ring_size;
+       int fd;
+};
+
+struct udebug_packet_info {
+       const char *attr[__UDEBUG_META_MAX];
+};
+
+struct udebug_remote_buf {
+       struct avl_node node;
+       struct udebug_buf buf;
+       bool poll;
+       uint32_t head;
+
+       /* provided by user */
+       uint32_t pcap_iface;
+       void *priv;
+       const struct udebug_packet_info *meta;
+};
+
+struct udebug {
+       struct list_head local_rings;
+       struct avl_tree remote_rings;
+       uint32_t next_id;
+       struct uloop_fd fd;
+       int poll_handle;
+       char *socket_path;
+       struct uloop_timeout reconnect;
+
+       /* filled by user */
+       void (*notify_cb)(struct udebug *ctx, struct udebug_remote_buf *rb);
+};
+
+struct udebug_ptr {
+       uint32_t start;
+       uint32_t len;
+       uint64_t timestamp;
+};
+
+struct udebug_snapshot {
+       struct udebug_ptr *entries;
+       unsigned int n_entries;
+       unsigned int dropped;
+       void *data;
+       size_t data_size;
+
+       uint32_t iter_idx;
+
+       enum udebug_format format;
+       uint32_t sub_format;
+
+       uint32_t rbuf_idx;
+};
+
+struct udebug_iter {
+       struct udebug_snapshot **list;
+       size_t n;
+
+       struct udebug_snapshot *s;
+       unsigned int s_idx;
+
+       uint64_t timestamp;
+       void *data;
+       size_t len;
+};
+
+uint64_t udebug_timestamp(void);
+
+void udebug_entry_init_ts(struct udebug_buf *buf, uint64_t timestamp);
+static inline void udebug_entry_init(struct udebug_buf *buf)
+{
+       udebug_entry_init_ts(buf, udebug_timestamp());
+}
+void *udebug_entry_append(struct udebug_buf *buf, const void *data, uint32_t len);
+int udebug_entry_printf(struct udebug_buf *buf, const char *fmt, ...);
+int udebug_entry_vprintf(struct udebug_buf *buf, const char *fmt, va_list ap);
+void udebug_entry_add(struct udebug_buf *buf);
+
+int udebug_buf_init(struct udebug_buf *buf, size_t entries, size_t size);
+int udebug_buf_add(struct udebug *ctx, struct udebug_buf *buf,
+                  const struct udebug_buf_meta *meta);
+uint64_t udebug_buf_flags(struct udebug_buf *buf);
+void udebug_buf_free(struct udebug_buf *buf);
+
+struct udebug_remote_buf *udebug_remote_buf_get(struct udebug *ctx, uint32_t id);
+int udebug_remote_buf_map(struct udebug *ctx, struct udebug_remote_buf *rb, uint32_t id);
+void udebug_remote_buf_unmap(struct udebug *ctx, struct udebug_remote_buf *rb);
+int udebug_remote_buf_set_poll(struct udebug *ctx, struct udebug_remote_buf *rb, bool val);
+void udebug_remote_buf_set_flags(struct udebug_remote_buf *rb, uint64_t mask, uint64_t set);
+struct udebug_snapshot *udebug_remote_buf_snapshot(struct udebug_remote_buf *rb);
+bool udebug_snapshot_get_entry(struct udebug_snapshot *s, struct udebug_iter *it, unsigned int entry);
+
+void udebug_remote_buf_set_start_time(struct udebug_remote_buf *rb, uint64_t ts);
+void udebug_remote_buf_set_start_offset(struct udebug_remote_buf *rb, uint32_t idx);
+
+void udebug_iter_start(struct udebug_iter *it, struct udebug_snapshot **s, size_t n);
+bool udebug_iter_next(struct udebug_iter *it);
+
+void udebug_init(struct udebug *ctx);
+int udebug_connect(struct udebug *ctx, const char *path);
+void udebug_auto_connect(struct udebug *ctx, const char *path);
+void udebug_add_uloop(struct udebug *ctx);
+void udebug_poll(struct udebug *ctx);
+void udebug_free(struct udebug *ctx);
+
+static inline bool udebug_is_connected(struct udebug *ctx)
+{
+       return ctx->fd.fd >= 0;
+}
+
+
+#endif