utils: Factor out hexdump code used by --enable-packet-dump.

Factor out the common code used to hexdump the protocol when
./configure --enable-packet-dump is used.

It's not quite a straight refactor because I had to fix some
signedness bugs in the code which were not revealed before because
this code is usually disabled.

(cherry picked from commit 2add3c6995)
This commit is contained in:
Richard W.M. Jones
2018-06-04 05:24:13 -04:00
parent c829f97054
commit 2f207f1393
4 changed files with 31 additions and 40 deletions

View File

@@ -70,6 +70,7 @@ extern int guestfs_int_is_fifo (int64_t mode);
extern int guestfs_int_is_lnk (int64_t mode);
extern int guestfs_int_is_sock (int64_t mode);
extern char *guestfs_int_full_path (const char *dir, const char *name);
extern void guestfs_int_hexdump (const void *data, size_t len, FILE *fp);
/* Not all language bindings know how to deal with Pointer arguments.
* Those that don't will use this macro which complains noisily and

View File

@@ -733,3 +733,29 @@ guestfs_int_full_path (const char *dir, const char *name)
return path;
}
/**
* Hexdump a block of memory to C<FILE *>, used for debugging.
*/
void
guestfs_int_hexdump (const void *data, size_t len, FILE *fp)
{
size_t i, j;
for (i = 0; i < len; i += 16) {
fprintf (fp, "%04zx: ", i);
for (j = i; j < MIN (i+16, len); ++j)
fprintf (fp, "%02x ", ((const unsigned char *)data)[j]);
for (; j < i+16; ++j)
fprintf (fp, " ");
fprintf (fp, "|");
for (j = i; j < MIN (i+16, len); ++j)
if (c_isprint (((const char *)data)[j]))
fprintf (fp, "%c", ((const char *)data)[j]);
else
fprintf (fp, ".");
for (; j < i+16; ++j)
fprintf (fp, " ");
fprintf (fp, "|\n");
}
}

View File

@@ -115,26 +115,8 @@ main_loop (int _sock)
exit (EXIT_FAILURE);
#ifdef ENABLE_PACKET_DUMP
if (verbose) {
size_t i, j;
for (i = 0; i < len; i += 16) {
printf ("%04zx: ", i);
for (j = i; j < MIN (i+16, len); ++j)
printf ("%02x ", (unsigned char) buf[j]);
for (; j < i+16; ++j)
printf (" ");
printf ("|");
for (j = i; j < MIN (i+16, len); ++j)
if (c_isprint (buf[j]))
printf ("%c", buf[j]);
else
printf (".");
for (; j < i+16; ++j)
printf (" ");
printf ("|\n");
}
}
if (verbose)
guestfs_int_hexdump (buf, len, stdout);
#endif
gettimeofday (&start_t, NULL);

View File

@@ -607,26 +607,8 @@ recv_from_daemon (guestfs_h *g, uint32_t *size_rtn, void **buf_rtn)
* it if we're debugging.
*/
#ifdef ENABLE_PACKET_DUMP
if (g->verbose) {
ssize_t i, j;
for (i = 0; i < n; i += 16) {
printf ("%04zx: ", i);
for (j = i; j < MIN (i+16, n); ++j)
printf ("%02x ", (*(unsigned char **)buf_rtn)[j]);
for (; j < i+16; ++j)
printf (" ");
printf ("|");
for (j = i; j < MIN (i+16, n); ++j)
if (c_isprint ((*(char **)buf_rtn)[j]))
printf ("%c", (*(char **)buf_rtn)[j]);
else
printf (".");
for (; j < i+16; ++j)
printf (" ");
printf ("|\n");
}
}
if (g->verbose)
guestfs_int_hexdump (buf_rtn, n, stdout);
#endif
return 0;