tizen_2.0 merged
[framework/system/dlog.git] / logutil.c
1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <stdbool.h>
21 #include <stdarg.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <time.h>
26 #include <sys/time.h>
27 #include <ctype.h>
28 #include <errno.h>
29 #include <assert.h>
30 #include <sys/stat.h>
31 #include <arpa/inet.h>
32
33
34 #include <logger.h>
35 #include <logprint.h>
36
37 #define DEFAULT_LOG_ROTATE_SIZE_KBYTES 16
38 #define DEFAULT_MAX_ROTATED_LOGS 4
39
40 #define LOG_FILE_DIR    "/dev/log_"
41
42 static log_format* g_logformat;
43 static bool g_nonblock = false;
44 static int g_tail_lines = 0;
45
46 static const char * g_output_filename = NULL;
47 static int g_log_rotate_size_kbytes = 0;                   // 0 means "no log rotation"
48 static int g_max_rotated_logs = DEFAULT_MAX_ROTATED_LOGS; // 0 means "unbounded"
49 static int g_outfd = -1;
50 static off_t g_out_byte_count = 0;
51 static int g_dev_count = 0;
52
53 struct queued_entry_t {
54         union {
55                 unsigned char buf[LOGGER_ENTRY_MAX_LEN + 1] __attribute__((aligned(4)));
56                 struct logger_entry entry __attribute__((aligned(4)));
57         };
58         struct queued_entry_t* next;
59 };
60
61 static int cmp(struct queued_entry_t* a, struct queued_entry_t* b)
62 {
63         int n = a->entry.sec - b->entry.sec;
64         if (n != 0)
65         {
66                 return n;
67         }
68         return a->entry.nsec - b->entry.nsec;
69 }
70
71
72 struct log_device_t {
73         char* device;
74         int fd;
75         bool printed;
76         struct queued_entry_t* queue;
77         struct log_device_t* next;
78 };
79
80 static void enqueue(struct log_device_t* device, struct queued_entry_t* entry)
81 {
82         if( device->queue == NULL)
83         {
84                 device->queue = entry;
85         }
86         else
87         {
88                 struct queued_entry_t** e = &device->queue;
89                 while(*e && cmp(entry, *e) >= 0 )
90                 {
91                         e = &((*e)->next);
92                 }
93                 entry->next = *e;
94                 *e = entry;
95     }
96 }
97
98 static int open_logfile (const char *pathname)
99 {
100     return open(pathname, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
101 }
102
103 static void rotate_logs()
104 {
105     int err;
106         int i;
107         char file0[256]={0};
108         char file1[256]={0};
109
110     // Can't rotate logs if we're not outputting to a file
111     if (g_output_filename == NULL) {
112         return;
113     }
114
115     close(g_outfd);
116
117     for (i = g_max_rotated_logs ; i > 0 ; i--)
118         {
119                 snprintf(file1, 255, "%s.%d", g_output_filename, i);
120
121                 if (i - 1 == 0) {
122                         snprintf(file0, 255, "%s", g_output_filename);
123                 } else {
124                         snprintf(file0, 255, "%s.%d", g_output_filename, i - 1);
125                 }
126
127                 err = rename (file0, file1);
128
129                 if (err < 0 && errno != ENOENT) {
130                         perror("while rotating log files");
131                 }
132     }
133
134     g_outfd = open_logfile (g_output_filename);
135
136     if (g_outfd < 0) {
137         perror ("couldn't open output file");
138         exit(-1);
139     }
140
141     g_out_byte_count = 0;
142
143 }
144
145
146 static void processBuffer(struct log_device_t* dev, struct logger_entry *buf)
147 {
148         int bytes_written = 0;
149         int err;
150         log_entry entry;
151         char mgs_buf[1024];
152
153         err = log_process_log_buffer(buf, &entry);
154
155         if (err < 0) {
156                 goto error;
157         }
158
159         if (log_should_print_line(g_logformat, entry.tag, entry.priority)) {
160                 if (false && g_dev_count > 1) {
161                         // FIXME
162                         mgs_buf[0] = dev->device[0];
163                         mgs_buf[1] = ' ';
164                         bytes_written = write(g_outfd, mgs_buf, 2);
165                         if (bytes_written < 0)
166                         {
167                                 perror("output error");
168                                 exit(-1);
169                         }
170                 }
171
172                 bytes_written = log_print_log_line(g_logformat, g_outfd, &entry);
173
174                 if (bytes_written < 0)
175                 {
176                         perror("output error");
177                         exit(-1);
178                 }
179         }
180
181         g_out_byte_count += bytes_written;
182
183     if (g_log_rotate_size_kbytes > 0 && (g_out_byte_count / 1024) >= g_log_rotate_size_kbytes)
184         {
185                 rotate_logs();
186         }
187
188 error:
189         //fprintf (stderr, "Error processing record\n");
190         return;
191 }
192
193 static void chooseFirst(struct log_device_t* dev, struct log_device_t** firstdev)
194 {
195         for (*firstdev = NULL; dev != NULL; dev = dev->next) {
196                 if (dev->queue != NULL && (*firstdev == NULL || cmp(dev->queue, (*firstdev)->queue) < 0))
197                 {
198                         *firstdev = dev;
199                 }
200         }
201 }
202
203 static void maybePrintStart(struct log_device_t* dev) {
204         if (!dev->printed) {
205                 dev->printed = true;
206                 if (g_dev_count > 1 ) {
207                         char buf[1024];
208                         snprintf(buf, sizeof(buf), "--------- beginning of %s\n", dev->device);
209                         if (write(g_outfd, buf, strlen(buf)) < 0) {
210                                 perror("output error");
211                                 exit(-1);
212                         }
213                 }
214         }
215 }
216
217 static void skipNextEntry(struct log_device_t* dev) {
218         maybePrintStart(dev);
219         struct queued_entry_t* entry = dev->queue;
220         dev->queue = entry->next;
221         free(entry);
222 }
223
224 static void printNextEntry(struct log_device_t* dev)
225 {
226         maybePrintStart(dev);
227         processBuffer(dev, &dev->queue->entry);
228         skipNextEntry(dev);
229 }
230
231
232 static void read_log_lines(struct log_device_t* devices)
233 {
234         struct log_device_t* dev;
235         int max = 0;
236         int ret;
237         int queued_lines = 0;
238         bool sleep = false; // for exit immediately when log buffer is empty and g_nonblock value is true.
239
240         int result;
241         fd_set readset;
242
243         for (dev=devices; dev; dev = dev->next) {
244                 if (dev->fd > max) {
245                         max = dev->fd;
246                 }
247         }
248
249         while (1) {
250                 do {
251                         struct timeval timeout = { 0, 5000 /* 5ms */ }; // If we oversleep it's ok, i.e. ignore EINTR.
252                         FD_ZERO(&readset);
253                         for (dev=devices; dev; dev = dev->next) {
254                                 FD_SET(dev->fd, &readset);
255                         }
256                         result = select(max + 1, &readset, NULL, NULL, sleep ? NULL : &timeout);
257                 } while (result == -1 && errno == EINTR);
258
259         if (result >= 0) {
260             for (dev=devices; dev; dev = dev->next) {
261                 if (FD_ISSET(dev->fd, &readset)) {
262                     struct queued_entry_t* entry = (struct queued_entry_t *)malloc(sizeof( struct queued_entry_t));
263                                         if (entry == NULL) {
264                                                 fprintf(stderr,"Can't malloc queued_entry\n");
265                                                 exit(-1);
266                                         }
267                                         entry->next = NULL;
268
269                     /* NOTE: driver guarantees we read exactly one full entry */
270                     ret = read(dev->fd, entry->buf, LOGGER_ENTRY_MAX_LEN);
271                     if (ret < 0) {
272                         if (errno == EINTR) {
273                             free(entry);
274                             goto next;
275                         }
276                         if (errno == EAGAIN) {
277                             free(entry);
278                             break;
279                         }
280                         perror("dlogutil read");
281                         exit(EXIT_FAILURE);
282                     }
283                     else if (!ret) {
284                         fprintf(stderr, "read: Unexpected EOF!\n");
285                         exit(EXIT_FAILURE);
286                     }
287
288                     entry->entry.msg[entry->entry.len] = '\0';
289
290                     enqueue(dev, entry);
291                     ++queued_lines;
292                 }
293             }
294
295             if (result == 0) {
296                 // we did our short timeout trick and there's nothing new
297                 // print everything we have and wait for more data
298                 sleep = true;
299                 while (true) {
300                     chooseFirst(devices, &dev);
301                     if (dev == NULL) {
302                         break;
303                     }
304                     if (g_tail_lines == 0 || queued_lines <= g_tail_lines) {
305                         printNextEntry(dev);
306                     } else {
307                         skipNextEntry(dev);
308                     }
309                     --queued_lines;
310                 }
311
312                 // the caller requested to just dump the log and exit
313                 if (g_nonblock) {
314                     exit(0);
315                 }
316             } else {
317                 // print all that aren't the last in their list
318                 sleep = false;
319                 while (g_tail_lines == 0 || queued_lines > g_tail_lines) {
320                     chooseFirst(devices, &dev);
321                     if (dev == NULL || dev->queue->next == NULL) {
322                         break;
323                     }
324                     if (g_tail_lines == 0) {
325                         printNextEntry(dev);
326                     } else {
327                         skipNextEntry(dev);
328                     }
329                     --queued_lines;
330                 }
331             }
332         }
333 next:
334         ;
335     }
336 }
337
338
339 static int clear_log(int logfd)
340 {
341     return ioctl(logfd, LOGGER_FLUSH_LOG);
342 }
343
344 /* returns the total size of the log's ring buffer */
345 static int get_log_size(int logfd)
346 {
347     return ioctl(logfd, LOGGER_GET_LOG_BUF_SIZE);
348 }
349
350 /* returns the readable size of the log's ring buffer (that is, amount of the log consumed) */
351 static int get_log_readable_size(int logfd)
352 {
353     return ioctl(logfd, LOGGER_GET_LOG_LEN);
354 }
355
356 static void setup_output()
357 {
358
359     if (g_output_filename == NULL) {
360         g_outfd = STDOUT_FILENO;
361
362     } else {
363         struct stat statbuf;
364
365         g_outfd = open_logfile (g_output_filename);
366
367         if (g_outfd < 0) {
368             perror ("couldn't open output file");
369             exit(-1);
370         }
371
372         fstat(g_outfd, &statbuf);
373
374         g_out_byte_count = statbuf.st_size;
375     }
376 }
377
378 static int set_log_format(const char * formatString)
379 {
380         static log_print_format format;
381
382         format = log_format_from_string(formatString);
383
384         if (format == FORMAT_OFF) {
385                 // FORMAT_OFF means invalid string
386                 return -1;
387         }
388
389         log_set_print_format(g_logformat, format);
390
391         return 0;
392 }
393
394 static void show_help(const char *cmd)
395 {
396     fprintf(stderr,"Usage: %s [options] [filterspecs]\n", cmd);
397
398     fprintf(stderr, "options include:\n"
399                     "  -s              Set default filter to silent.\n"
400                     "                  Like specifying filterspec '*:s'\n"
401                     "  -f <filename>   Log to file. Default to stdout\n"
402                     "  -r [<kbytes>]   Rotate log every kbytes. (16 if unspecified). Requires -f\n"
403                     "  -n <count>      Sets max number of rotated logs to <count>, default 4\n"
404                     "  -v <format>     Sets the log print format, where <format> is one of:\n\n"
405                     "                  brief process tag thread raw time threadtime long\n\n"
406                     "  -c              clear (flush) the entire log and exit\n"
407                     "  -d              dump the log and then exit (don't block)\n"
408                     "  -t <count>      print only the most recent <count> lines (implies -d)\n"
409                     "  -g              get the size of the log's ring buffer and exit\n"
410                     "  -b <buffer>     request alternate ring buffer\n"
411                     "                  ('main' (default), 'radio', 'system')");
412
413
414     fprintf(stderr,"\nfilterspecs are a series of \n"
415                    "  <tag>[:priority]\n\n"
416                    "where <tag> is a log component tag (or * for all) and priority is:\n"
417                    "  V    Verbose\n"
418                    "  D    Debug\n"
419                    "  I    Info\n"
420                    "  W    Warn\n"
421                    "  E    Error\n"
422                    "  F    Fatal\n"
423                    "  S    Silent (supress all output)\n"
424                    "\n'*' means '*:d' and <tag> by itself means <tag>:v\n"
425                    "If no filterspec is found, filter defaults to '*:I'\n"
426                    "\nIf not specified with -v, format is set defaults to \"brief\"\n\n");
427
428
429
430 }
431
432
433 int main(int argc, char **argv)
434 {
435     int err;
436     int has_set_log_format = 0;
437     int is_clear_log = 0;
438     int getLogSize = 0;
439     int mode = O_RDONLY;
440         int i;
441 //    const char *forceFilters = NULL;
442         struct log_device_t* devices = NULL;
443         struct log_device_t* dev;
444
445     g_logformat = (log_format *)log_format_new();
446
447     if (argc == 2 && 0 == strcmp(argv[1], "--test")) {
448         logprint_run_tests();
449         exit(0);
450     }
451
452     if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
453         show_help(argv[0]);
454         exit(0);
455     }
456
457     for (;;) {
458         int ret;
459
460         ret = getopt(argc, argv, "cdt:gsf:r:n:v:b:D");
461
462         if (ret < 0) {
463             break;
464         }
465
466         switch(ret) {
467             case 's':
468                 // default to all silent
469                 log_add_filter_rule(g_logformat, "*:s");
470             break;
471
472             case 'c':
473                 is_clear_log = 1;
474                 mode = O_WRONLY;
475             break;
476
477             case 'd':
478                 g_nonblock = true;
479             break;
480
481             case 't':
482                 g_nonblock = true;
483                 g_tail_lines = atoi(optarg);
484             break;
485
486
487             case 'g':
488                 getLogSize = 1;
489             break;
490
491                         case 'b': {
492                                                   char* buf = (char*) malloc(strlen(LOG_FILE_DIR) + strlen(optarg) + 1);
493                                                   if (buf == NULL) {
494                                                           fprintf(stderr,"Can't malloc LOG_FILE_DIR\n");
495                                                           exit(-1);
496                                                   }
497                                                   strcpy(buf, LOG_FILE_DIR);
498                                                   strcat(buf, optarg);
499                                                   //            snprintf(buf, strlen(LOG_FILE_DIR) + strlen(optarg) + 1, "%s%s", LOG_FILE_DIR, optarg);
500
501                 if (devices) {
502                                         dev = devices;
503                     while (dev->next) {
504                                                 dev = dev->next;
505                                         }
506                                         dev->next = (struct log_device_t *)malloc( sizeof(struct log_device_t));
507                                         if (dev->next == NULL) {
508                                                 fprintf(stderr,"Can't malloc log_device\n");
509                                                 exit(-1);
510                                         }
511                                         dev->next->device = buf;
512                                         dev->next->fd = -1;
513                                         dev->next->printed = false;
514                                         dev->next->queue = NULL;
515                                         dev->next->next = NULL;
516
517                 } else {
518                                         devices = (struct log_device_t *)malloc( sizeof(struct log_device_t));
519                                         if (devices == NULL) {
520                                                 fprintf(stderr,"Can't malloc log_device\n");
521                                                 exit(-1);
522                                         }
523                                         devices->device = buf;
524                                         devices->fd = -1;
525                                         devices->printed = false;
526                                         devices->queue = NULL;
527                                         devices->next = NULL;
528                 }
529                 g_dev_count++;
530             }
531             break;
532
533             case 'f':
534                 // redirect output to a file
535
536                 g_output_filename = optarg;
537
538             break;
539
540             case 'r':
541 //                if (optarg == NULL) {
542 //                                      fprintf(stderr,"optarg == null\n");
543  //                  g_log_rotate_size_kbytes = DEFAULT_LOG_ROTATE_SIZE_KBYTES;
544  //              } else {
545                     //long logRotateSize;
546                     //char *lastDigit;
547
548                     if (!isdigit(optarg[0])) {
549                         fprintf(stderr,"Invalid parameter to -r\n");
550                         show_help(argv[0]);
551                         exit(-1);
552                     }
553                     g_log_rotate_size_kbytes = atoi(optarg);
554    //             }
555             break;
556
557             case 'n':
558                 if (!isdigit(optarg[0])) {
559                     fprintf(stderr,"Invalid parameter to -r\n");
560                     show_help(argv[0]);
561                     exit(-1);
562                 }
563
564                 g_max_rotated_logs = atoi(optarg);
565             break;
566
567             case 'v':
568                 err = set_log_format (optarg);
569                 if (err < 0) {
570                     fprintf(stderr,"Invalid parameter to -v\n");
571                     show_help(argv[0]);
572                     exit(-1);
573                 }
574
575                 has_set_log_format = 1;
576             break;
577
578                         default:
579                                 fprintf(stderr,"Unrecognized Option\n");
580                                 show_help(argv[0]);
581                                 exit(-1);
582                         break;
583                 }
584         }
585
586         if (!devices) {
587         devices = (struct log_device_t *)malloc( sizeof(struct log_device_t));
588                 if (devices == NULL) {
589                         fprintf(stderr,"Can't malloc log_device\n");
590                         exit(-1);
591                 }
592                 devices->device = strdup("/dev/"LOGGER_LOG_MAIN);
593                 devices->fd = -1;
594                 devices->printed = false;
595                 devices->queue = NULL;
596                 devices->next = NULL;
597         g_dev_count = 1;
598
599
600         int accessmode =
601                   (mode & O_RDONLY) ? R_OK : 0
602                 | (mode & O_WRONLY) ? W_OK : 0;
603
604         // only add this if it's available
605         if (0 == access("/dev/"LOGGER_LOG_SYSTEM, accessmode)) {
606                 devices->next = (struct log_device_t *)malloc( sizeof(struct log_device_t));
607                 if (devices->next == NULL) {
608                         fprintf(stderr,"Can't malloc log_device\n");
609                         exit(-1);
610                 }
611                 devices->next->device = strdup("/dev/"LOGGER_LOG_SYSTEM);
612                 devices->next->fd = -1;
613                 devices->next->printed = false;
614                 devices->next->queue = NULL;
615                 devices->next->next = NULL;
616                 g_dev_count ++;
617         }
618         if (0 == access("/dev/"LOGGER_LOG_APPS, accessmode)) {
619                 devices->next = (struct log_device_t *)malloc( sizeof(struct log_device_t));
620                 if (devices->next == NULL) {
621                         fprintf(stderr,"Can't malloc log_device\n");
622                         exit(-1);
623                 }
624                 devices->next->device = strdup("/dev/"LOGGER_LOG_APPS);
625                 devices->next->fd = -1;
626                 devices->next->printed = false;
627                 devices->next->queue = NULL;
628                 devices->next->next = NULL;
629                 g_dev_count ++;
630         }
631 /*
632         // only add this if it's available
633         int fd;
634         if ((fd = open("/dev/"LOGGER_LOG_SYSTEM, mode)) != -1) {
635                 devices->next = (struct log_device_t *)malloc( sizeof(struct log_device_t));
636                 devices->next->device = strdup("/dev/"LOGGER_LOG_SYSTEM);
637                 devices->next->fd = -1;
638                 devices->next->printed = false;
639                 devices->next->queue = NULL;
640                 devices->next->next = NULL;
641                 g_dev_count ++;
642
643                 close(fd);
644         }
645 */
646     }
647
648     if (g_log_rotate_size_kbytes != 0 && g_output_filename == NULL)
649         {
650                 fprintf(stderr,"-r requires -f as well\n");
651                 show_help(argv[0]);
652                 exit(-1);
653         }
654
655     setup_output();
656
657
658         if (has_set_log_format == 0) {
659                 err = set_log_format("brief");
660         }
661 /*
662                 const char* logFormat = getenv("DLOG_PRINTF_LOG");
663
664                 if (logFormat != NULL) {
665                         err = set_log_format("brief");
666
667                         if (err < 0) {
668                                 fprintf(stderr, "invalid format in DLOG_PRINTF_LOG '%s'\n", logFormat);
669                         }
670                 }
671         }
672         if (forceFilters) {
673                 err = log_add_filter_string(g_logformat, forceFilters);
674                 if (err < 0) {
675                         fprintf (stderr, "Invalid filter expression in -logcat option\n");
676                         exit(0);
677                 }
678         } else if (argc == optind) {
679         // Add from environment variable
680                 char *env_tags_orig = getenv("DLOG_LOG_TAGS");
681
682                 if (env_tags_orig != NULL) {
683                         err = log_add_filter_string(g_logformat, env_tags_orig);
684
685                         if (err < 0) {
686                                 fprintf(stderr, "Invalid filter expression in DLOG_LOG_TAGS\n");
687                                 show_help(argv[0]);
688                                 exit(-1);
689                         }
690                 }
691         } else {
692         // Add from commandline
693 */
694         fprintf(stderr,"arc = %d, optind = %d ,Kb %d, rotate %d\n", argc, optind,g_log_rotate_size_kbytes,g_max_rotated_logs);
695
696         if(argc == optind )
697         {
698                 // Add from environment variable
699         //char *env_tags_orig = getenv("DLOG_TAGS");
700                 log_add_filter_string(g_logformat, "*:d");
701         }
702         else
703         {
704
705                 for (i = optind ; i < argc ; i++) {
706                         err = log_add_filter_string(g_logformat, argv[i]);
707
708                         if (err < 0) {
709                                 fprintf (stderr, "Invalid filter expression '%s'\n", argv[i]);
710                                 show_help(argv[0]);
711                                 exit(-1);
712                         }
713                 }
714         }
715 /*
716     }
717 */
718     dev = devices;
719     while (dev) {
720         dev->fd = open(dev->device, mode);
721         if (dev->fd < 0) {
722             fprintf(stderr, "Unable to open log device '%s': %s\n",
723                 dev->device, strerror(errno));
724             exit(EXIT_FAILURE);
725         }
726
727         if (is_clear_log) {
728             int ret;
729             ret = clear_log(dev->fd);
730             if (ret) {
731                 perror("ioctl");
732                 exit(EXIT_FAILURE);
733             }
734         }
735
736         if (getLogSize) {
737             int size, readable;
738
739             size = get_log_size(dev->fd);
740             if (size < 0) {
741                 perror("ioctl");
742                 exit(EXIT_FAILURE);
743             }
744
745             readable = get_log_readable_size(dev->fd);
746             if (readable < 0) {
747                 perror("ioctl");
748                 exit(EXIT_FAILURE);
749             }
750
751             printf("%s: ring buffer is %dKb (%dKb consumed), "
752                    "max entry is %db, max payload is %db\n", dev->device,
753                    size / 1024, readable / 1024,
754                    (int) LOGGER_ENTRY_MAX_LEN, (int) LOGGER_ENTRY_MAX_PAYLOAD);
755         }
756
757         dev = dev->next;
758     }
759
760     if (getLogSize) {
761         return 0;
762     }
763
764     if (is_clear_log) {
765         return 0;
766     }
767
768     read_log_lines(devices);
769
770     return 0;
771 }