main.cc
#include <stdint.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <iostream>
#include <iomanip>
 
#define OK 0
 
#define UNIVERSAL_SURVIVAL_TRACE(p_message) std::cerr << "WARNING:  " << __FILE__ << ":" << __LINE__ << ":" << __PRETTY_FUNCTION__ << "  " << p_message << std::endl
 
#define THROW(p_exception, p_message)    \
  do                                     \
  {                                      \
    UNIVERSAL_SURVIVAL_TRACE(p_message); \
    throw p_exception;                   \
  }                                      \
  while (0)
 
#define ASSERTION_CHECKER(p_assertion, p_message) if (!(p_assertion)) THROW(-1, p_message)
 
#define RETURN(p_return, p_assertion, p_message) \
  do                                             \
  {                                              \
    if (!(p_assertion))                          \
    {                                            \
      UNIVERSAL_SURVIVAL_TRACE(p_message);       \
    }                                            \
    return p_return;                             \
  }                                              \
  while (0)
 
#define RETURN_WITH_DEFAULT_ASSERTION(p_return, p_message) RETURN(p_return, result == OK, p_message)
 
#define BREAK_IF(p_condition) if (p_condition) break
#define CONTINUE_IF(p_condition) if (p_condition) continue
 
#define DEFAULT_CATCH                       \
  catch (...)                               \
  {                                         \
    result = (result == OK ? !OK : result); \
  }
 
int main
(
  int       p_argc  ,
  char  **  p_argv
)
{
  int     result  =  !OK   ;
  int     fd      =  -1    ;
  size_t  length  =  0     ;
  char *  addr    =  NULL  ;
  try
  {
    do
    {
      ASSERTION_CHECKER(2 <= p_argc, "");
      fd = open(p_argv[1], O_RDWR);
      ASSERTION_CHECKER(fd != -1, "");
      struct stat sb;
      ASSERTION_CHECKER(fstat(fd, &sb) != -1, "");
      length = sb.st_size;
      BREAK_IF(!length);
      addr = (char *)mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
      ASSERTION_CHECKER(addr != MAP_FAILED, "");
      std::cout << std::hex << std::setfill('0') << std::uppercase;
      for (size_t idx = 0; idx < length; ++idx)
      {
        std::cout << std::setw(2) << (uint16_t)(((unsigned char *)addr)[idx]) << " ";
      }
      std::cout << std::endl;
    }
    while (0);
    result = OK;
  }
  DEFAULT_CATCH;
  result = ((fd != -1) && (close(fd)            == -1) ? !OK : result);
  result = (addr       && (munmap(addr, length) == -1) ? !OK : result);
  RETURN_WITH_DEFAULT_ASSERTION(result, "");
}
mmap.txt · Last modified: 2022/04/16 12:23 (external edit)
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki