现在的位置: 首页 > 综合 > 正文

mapper.c 小工具

2017年08月27日 ⁄ 综合 ⁄ 共 2230字 ⁄ 字号 评论关闭
  1. /* 
  2.  * mapper.c -- simple file that mmap()s a file region and prints it 
  3.  * 
  4.  * Copyright (C) 1998,2000,2001 Alessandro Rubini 
  5.  *  
  6.  *   This program is free software; you can redistribute it and/or modify 
  7.  *   it under the terms of the GNU General Public License as published by 
  8.  *   the Free Software Foundation; either version 2 of the License, or 
  9.  *   (at your option) any later version. 
  10.  * 
  11.  *   This program is distributed in the hope that it will be useful, 
  12.  *   but WITHOUT ANY WARRANTY; without even the implied warranty of 
  13.  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
  14.  *   GNU General Public License for more details. 
  15.  * 
  16.  *   You should have received a copy of the GNU General Public License 
  17.  *   along with this program; if not, write to the Free Software 
  18.  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. 
  19.  */  
  20.   
  21. #include <stdio.h>
      
  22. #include <stdlib.h>   
  23. #include <string.h>
      
  24. #include <unistd.h>   
  25. #include <sys/mman.h>
      
  26. #include <errno.h>   
  27. #include <limits.h>
      
  28.   
  29. int main(int argc, char **argv)  
  30. {  
  31.     char *fname;  
  32.     FILE *f;  
  33.     unsigned long offset, len;  
  34.     void *address;  
  35.   
  36.     if (argc !=4  
  37.        || sscanf(argv[2],"%li", &offset) != 1  
  38.        || sscanf(argv[3],"%li", &len) != 1) {  
  39.         fprintf(stderr, "%s: Usage \"%s <file> <offset> <len>\"\n", argv[0],  
  40.                 argv[0]);  
  41.         exit(1);  
  42.     }  
  43.     /* the offset might be big (e.g., PCI devices), but conversion trims it */  
  44.     if (offset == INT_MAX) {  
  45.     if (argv[2][1]=='x')  
  46.             sscanf(argv[2]+2, "%lx", &offset);  
  47.         else  
  48.             sscanf(argv[2], "%lu", &offset);  
  49.     }  
  50.   
  51.     fname=argv[1];  
  52.   
  53.     if (!(f=fopen(fname,"r"))) {  
  54.         fprintf(stderr, "%s: %s: %s\n", argv[0], fname, strerror(errno));  
  55.         exit(1);  
  56.     }  
  57.   
  58.     address=mmap(0, len, PROT_READ, MAP_FILE | MAP_PRIVATE, fileno(f), offset);  
  59.   
  60.     if (address == (void *)-1) {  
  61.         fprintf(stderr,"%s: mmap(): %s\n",argv[0],strerror(errno));  
  62.         exit(1);  
  63.     }  
  64.     fclose(f);  
  65.     fprintf(stderr, "mapped \"%s\" from %lu (0x%08lx) to %lu (0x%08lx)\n",  
  66.             fname, offset, offset, offset+len, offset+len);  
  67.   
  68.     fwrite(address, 1, len, stdout);  
  69.     pause();  
  70.     return 0;  
  71. }  

抱歉!评论已关闭.