Debian Codegraph @

src/bin/dwarfexample/simplecrc.c

raw
1 /* Copyright (C) 2020 David Anderson. 2020.
2 This small program is hereby
3 placed into the public domain to be copied or
4 used by anyone for any purpose.
5
6 It is not tested nor normally built,
7 it is just in case one wants
8 to redo a crc calculation on a file.
9 In a build directory compile something like this:
10
11 cc -Ilibdwarf $HOME/dwarf/code/dwarfexample/simplecrc.c \
12 libdwarf/.libs/libdwarf.a -lz
13 */
14
15 #include <stdio.h>
16 #include <stdlib.h> /* for exit(), C89 malloc */
17 #include <unistd.h> /* for close */
18 #include <sys/types.h> /* for off_t ssize_t */
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <malloc.h>
22 #include <string.h> /* for memset */
23 #include "dwarf.h"
24 #include "libdwarf.h"
25
26 static void
27 simple_test(const char *fname)
28 {
29 int fd = 0;
30 off_t size_left = 0;
31 off_t fsize = 0;
32 off_t lsval = 0;
33 ssize_t readlen = 1000;
34 unsigned char *readbuf = 0;
35 ssize_t readval = 0;
36 unsigned int tcrc = 0;
37 unsigned int init = 0;
38
39 printf("File: %s\n",fname);
40 fd = open(fname,O_RDONLY);
41 if (fd < 0) {
42 printf("no such file\n");
43 return;
44 }
45 {
46 fsize = size_left = lseek(fd,0L,SEEK_END);
47 printf("file size %lu (0x%lx)\n",(unsigned long)fsize,
48 (unsigned long)fsize);
49 if (fsize == (off_t)-1) {
50 printf("Fail 22\n");
51 exit(EXIT_FAILURE);
52 }
53 }
54 if (fsize <= (off_t)500) {
55 /* Not a real object file.
56 A random length check. */
57 printf("Fail 21\n");
58 exit(EXIT_FAILURE);
59 }
60 lsval = lseek(fd,0L,SEEK_SET);
61 if (lsval < 0) {
62 printf("Fail 1\n");
63 exit(EXIT_FAILURE);
64 }
65 readbuf = (unsigned char *)malloc(readlen);
66 if (!readbuf) {
67 printf("Fail 2\n");
68 exit(EXIT_FAILURE);
69 }
70 while (size_left > 0) {
71 if (size_left < readlen) {
72 readlen = size_left;
73 }
74 readval = read(fd,readbuf,readlen);
75 if (readval != (ssize_t)readlen) {
76 printf("Fail 3\n");
77 exit(EXIT_FAILURE);
78 }
79 size_left -= readlen;
80 tcrc = dwarf_basic_crc32(readbuf,readlen,init);
81 init = tcrc;
82 }
83 }
84
85 int
86 main(int argc, char **argv)
87 {
88 const char *fname = 0;
89
90 (void)argc;
91 (void)argv;
92
93 fname = "/usr/lib/debug/.build-id/1c/"
94 "2d642ffb01d1894d3c7dba050fcd160580a3e1.debug";
95 simple_test(fname);
96
97 fname = "/usr/bin/gdb";
98 simple_test(fname);
99 fname = "/home/davea/dwarf/code/dwarfexample"
100 "/dummyexecutable.debug";
101 simple_test(fname);
102
103 }