I’m studying the code of the netstat tool (Linux), which AFAIK mostly reads a /proc/net/tcp file and dowa pretty-printing out of it. (My focus is on the -t mode right now.)
I’m a bit puzzled by the coding style the authors have chosen:
static int tcp_info(void)
{
INFO_GUTS6(_PATH_PROCNET_TCP, _PATH_PROCNET_TCP6, "AF INET (tcp)", tcp_do_one);
}
where
#define INFO_GUTS6(file,file6,name,proc) \
char buffer[8192]; \
int rc = 0; \
int lnr = 0; \
if (!flag_arg || flag_inet) { \
INFO_GUTS1(file,name,proc) \
} \
if (!flag_arg || flag_inet6) { \
INFO_GUTS2(file6,proc) \
} \
INFO_GUTS3
where
#define INFO_GUTS3 \
return rc;
and
#if HAVE_AFINET6
#define INFO_GUTS2(file,proc) \
lnr = 0; \
procinfo = fopen((file), "r"); \
if (procinfo != NULL) { \
do { \
if (fgets(buffer, sizeof(buffer), procinfo)) \
(proc)(lnr++, buffer); \
} while (!feof(procinfo)); \
fclose(procinfo); \
}
#else
#define INFO_GUTS2(file,proc)
#endif
etc.
Clearly, my coding sense is tilting and says “those should be functions”. I don’t see any benefit those macros bring here. It kills readability, etc.
Is anybody around familiar with this code, can shed some light on what “INFO_GUTS” is about here and whether there could have been (or still has) a reason for such an odd coding style?
In case you’re curious about their use, the full dependency graph goes like this:
# /---> INFO_GUTS1 <---\
# INFO_GUTS --* INFO_GUTS2 <----*---- INFO_GUTS6
# î \---> INFO_GUTS3 <---/ î
# | |
# unix_info() igmp_info(), tcp_info(), udp_info(), raw_info()
It reads as someones terrible idea to implement optional IPv6 support. You would have to walk through the history to confirm, but the archive only seems to go back to 1.46 and the implied damage is at 1.20+.
I found a git archive going back to 1.24 and it is still there. Older code looks doubtful.
Neither BusyBox or BSD code includes such messy code. So it appeared in the Linux version and suffered major bit rot.