• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007-2016 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 #include "pmsg_reader.h"
18 
19 #include <ctype.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/types.h>
25 
26 #include <cutils/list.h>
27 #include <private/android_logger.h>
28 
29 #include "logger.h"
30 
PmsgRead(struct logger_list * logger_list,struct log_msg * log_msg)31 int PmsgRead(struct logger_list* logger_list, struct log_msg* log_msg) {
32   ssize_t ret;
33   off_t current, next;
34   struct __attribute__((__packed__)) {
35     android_pmsg_log_header_t p;
36     android_log_header_t l;
37     uint8_t prio;
38   } buf;
39   static uint8_t preread_count;
40 
41   memset(log_msg, 0, sizeof(*log_msg));
42 
43   if (atomic_load(&logger_list->fd) <= 0) {
44     int i, fd = open("/sys/fs/pstore/pmsg-ramoops-0", O_RDONLY | O_CLOEXEC);
45 
46     if (fd < 0) {
47       return -errno;
48     }
49     if (fd == 0) { /* Argggg */
50       fd = open("/sys/fs/pstore/pmsg-ramoops-0", O_RDONLY | O_CLOEXEC);
51       close(0);
52       if (fd < 0) {
53         return -errno;
54       }
55     }
56     i = atomic_exchange(&logger_list->fd, fd);
57     if ((i > 0) && (i != fd)) {
58       close(i);
59     }
60     preread_count = 0;
61   }
62 
63   while (1) {
64     int fd;
65 
66     if (preread_count < sizeof(buf)) {
67       fd = atomic_load(&logger_list->fd);
68       if (fd <= 0) {
69         return -EBADF;
70       }
71       ret = TEMP_FAILURE_RETRY(read(fd, &buf.p.magic + preread_count, sizeof(buf) - preread_count));
72       if (ret < 0) {
73         return -errno;
74       }
75       preread_count += ret;
76     }
77     if (preread_count != sizeof(buf)) {
78       return preread_count ? -EIO : -EAGAIN;
79     }
80     if ((buf.p.magic != LOGGER_MAGIC) || (buf.p.len <= sizeof(buf)) ||
81         (buf.p.len > (sizeof(buf) + LOGGER_ENTRY_MAX_PAYLOAD)) || (buf.l.id >= LOG_ID_MAX) ||
82         (buf.l.realtime.tv_nsec >= NS_PER_SEC) ||
83         ((buf.l.id != LOG_ID_EVENTS) && (buf.l.id != LOG_ID_SECURITY) &&
84          ((buf.prio == ANDROID_LOG_UNKNOWN) || (buf.prio == ANDROID_LOG_DEFAULT) ||
85           (buf.prio >= ANDROID_LOG_SILENT)))) {
86       do {
87         memmove(&buf.p.magic, &buf.p.magic + 1, --preread_count);
88       } while (preread_count && (buf.p.magic != LOGGER_MAGIC));
89       continue;
90     }
91     preread_count = 0;
92 
93     if ((logger_list->log_mask & (1 << buf.l.id)) &&
94         ((!logger_list->start.tv_sec && !logger_list->start.tv_nsec) ||
95          ((logger_list->start.tv_sec <= buf.l.realtime.tv_sec) &&
96           ((logger_list->start.tv_sec != buf.l.realtime.tv_sec) ||
97            (logger_list->start.tv_nsec <= buf.l.realtime.tv_nsec)))) &&
98         (!logger_list->pid || (logger_list->pid == buf.p.pid))) {
99       char* msg = reinterpret_cast<char*>(&log_msg->entry) + sizeof(log_msg->entry);
100       *msg = buf.prio;
101       fd = atomic_load(&logger_list->fd);
102       if (fd <= 0) {
103         return -EBADF;
104       }
105       ret = TEMP_FAILURE_RETRY(read(fd, msg + sizeof(buf.prio), buf.p.len - sizeof(buf)));
106       if (ret < 0) {
107         return -errno;
108       }
109       if (ret != (ssize_t)(buf.p.len - sizeof(buf))) {
110         return -EIO;
111       }
112 
113       log_msg->entry.len = buf.p.len - sizeof(buf) + sizeof(buf.prio);
114       log_msg->entry.hdr_size = sizeof(log_msg->entry);
115       log_msg->entry.pid = buf.p.pid;
116       log_msg->entry.tid = buf.l.tid;
117       log_msg->entry.sec = buf.l.realtime.tv_sec;
118       log_msg->entry.nsec = buf.l.realtime.tv_nsec;
119       log_msg->entry.lid = buf.l.id;
120       log_msg->entry.uid = buf.p.uid;
121 
122       return ret + sizeof(buf.prio) + log_msg->entry.hdr_size;
123     }
124 
125     fd = atomic_load(&logger_list->fd);
126     if (fd <= 0) {
127       return -EBADF;
128     }
129     current = TEMP_FAILURE_RETRY(lseek(fd, (off_t)0, SEEK_CUR));
130     if (current < 0) {
131       return -errno;
132     }
133     fd = atomic_load(&logger_list->fd);
134     if (fd <= 0) {
135       return -EBADF;
136     }
137     next = TEMP_FAILURE_RETRY(lseek(fd, (off_t)(buf.p.len - sizeof(buf)), SEEK_CUR));
138     if (next < 0) {
139       return -errno;
140     }
141     if ((next - current) != (ssize_t)(buf.p.len - sizeof(buf))) {
142       return -EIO;
143     }
144   }
145 }
146 
PmsgClose(struct logger_list * logger_list)147 void PmsgClose(struct logger_list* logger_list) {
148   int fd = atomic_exchange(&logger_list->fd, 0);
149   if (fd > 0) {
150     close(fd);
151   }
152 }
153 
realloc_or_free(void * ptr,size_t new_size)154 static void* realloc_or_free(void* ptr, size_t new_size) {
155   void* result = realloc(ptr, new_size);
156   if (!result) {
157     free(ptr);
158   }
159   return result;
160 }
161 
__android_log_pmsg_file_read(log_id_t logId,char prio,const char * prefix,__android_log_pmsg_file_read_fn fn,void * arg)162 ssize_t __android_log_pmsg_file_read(log_id_t logId, char prio, const char* prefix,
163                                      __android_log_pmsg_file_read_fn fn, void* arg) {
164   ssize_t ret;
165   struct content {
166     struct listnode node;
167     struct logger_entry entry;
168   } * content;
169   struct names {
170     struct listnode node;
171     struct listnode content;
172     log_id_t id;
173     char prio;
174     char name[];
175   } * names;
176   struct listnode name_list;
177   struct listnode *node, *n;
178   size_t len, prefix_len;
179 
180   if (!fn) {
181     return -EINVAL;
182   }
183 
184   /* Add just enough clues in logger_list and transp to make API function */
185   struct logger_list logger_list = {
186       .mode = static_cast<int>(ANDROID_LOG_PSTORE | ANDROID_LOG_NONBLOCK),
187       .log_mask = (unsigned)-1};
188   if (logId != LOG_ID_ANY) {
189     logger_list.log_mask = (1 << logId);
190   }
191   logger_list.log_mask &= ~((1 << LOG_ID_KERNEL) | (1 << LOG_ID_EVENTS) | (1 << LOG_ID_SECURITY));
192   if (!logger_list.log_mask) {
193     return -EINVAL;
194   }
195 
196   /* Initialize name list */
197   list_init(&name_list);
198 
199   ret = SSIZE_MAX;
200 
201   /* Validate incoming prefix, shift until it contains only 0 or 1 : or / */
202   prefix_len = 0;
203   if (prefix) {
204     const char *prev = NULL, *last = NULL, *cp = prefix;
205     while ((cp = strpbrk(cp, "/:"))) {
206       prev = last;
207       last = cp;
208       cp = cp + 1;
209     }
210     if (prev) {
211       prefix = prev + 1;
212     }
213     prefix_len = strlen(prefix);
214   }
215 
216   /* Read the file content */
217   log_msg log_msg;
218   while (PmsgRead(&logger_list, &log_msg) > 0) {
219     const char* cp;
220     size_t hdr_size = log_msg.entry.hdr_size;
221 
222     char* msg = (char*)&log_msg + hdr_size;
223     const char* split = NULL;
224 
225     if (hdr_size != sizeof(log_msg.entry)) {
226       continue;
227     }
228     /* Check for invalid sequence number */
229     if (log_msg.entry.nsec % ANDROID_LOG_PMSG_FILE_SEQUENCE ||
230         (log_msg.entry.nsec / ANDROID_LOG_PMSG_FILE_SEQUENCE) >=
231             ANDROID_LOG_PMSG_FILE_MAX_SEQUENCE) {
232       continue;
233     }
234 
235     /* Determine if it has <dirbase>:<filebase> format for tag */
236     len = log_msg.entry.len - sizeof(prio);
237     for (cp = msg + sizeof(prio); *cp && isprint(*cp) && !isspace(*cp) && --len; ++cp) {
238       if (*cp == ':') {
239         if (split) {
240           break;
241         }
242         split = cp;
243       }
244     }
245     if (*cp || !split) {
246       continue;
247     }
248 
249     /* Filters */
250     if (prefix_len && strncmp(msg + sizeof(prio), prefix, prefix_len)) {
251       size_t offset;
252       /*
253        *   Allow : to be a synonym for /
254        * Things we do dealing with const char * and do not alloc
255        */
256       split = strchr(prefix, ':');
257       if (split) {
258         continue;
259       }
260       split = strchr(prefix, '/');
261       if (!split) {
262         continue;
263       }
264       offset = split - prefix;
265       if ((msg[offset + sizeof(prio)] != ':') || strncmp(msg + sizeof(prio), prefix, offset)) {
266         continue;
267       }
268       ++offset;
269       if ((prefix_len > offset) &&
270           strncmp(&msg[offset + sizeof(prio)], split + 1, prefix_len - offset)) {
271         continue;
272       }
273     }
274 
275     if ((prio != ANDROID_LOG_ANY) && (*msg < prio)) {
276       continue;
277     }
278 
279     /* check if there is an existing entry */
280     list_for_each(node, &name_list) {
281       names = node_to_item(node, struct names, node);
282       if (!strcmp(names->name, msg + sizeof(prio)) && names->id == log_msg.entry.lid &&
283           names->prio == *msg) {
284         break;
285       }
286     }
287 
288     /* We do not have an existing entry, create and add one */
289     if (node == &name_list) {
290       static const char numbers[] = "0123456789";
291       unsigned long long nl;
292 
293       len = strlen(msg + sizeof(prio)) + 1;
294       names = static_cast<struct names*>(calloc(1, sizeof(*names) + len));
295       if (!names) {
296         ret = -ENOMEM;
297         break;
298       }
299       strcpy(names->name, msg + sizeof(prio));
300       names->id = static_cast<log_id_t>(log_msg.entry.lid);
301       names->prio = *msg;
302       list_init(&names->content);
303       /*
304        * Insert in reverse numeric _then_ alpha sorted order as
305        * representative of log rotation:
306        *
307        *   log.10
308        *   klog.10
309        *   . . .
310        *   log.2
311        *   klog.2
312        *   log.1
313        *   klog.1
314        *   log
315        *   klog
316        *
317        * thus when we present the content, we are provided the oldest
318        * first, which when 'refreshed' could spill off the end of the
319        * pmsg FIFO but retaining the newest data for last with best
320        * chances to survive.
321        */
322       nl = 0;
323       cp = strpbrk(names->name, numbers);
324       if (cp) {
325         nl = strtoull(cp, NULL, 10);
326       }
327       list_for_each_reverse(node, &name_list) {
328         struct names* a_name = node_to_item(node, struct names, node);
329         const char* r = a_name->name;
330         int compare = 0;
331 
332         unsigned long long nr = 0;
333         cp = strpbrk(r, numbers);
334         if (cp) {
335           nr = strtoull(cp, NULL, 10);
336         }
337         if (nr != nl) {
338           compare = (nl > nr) ? 1 : -1;
339         }
340         if (compare == 0) {
341           compare = strcmp(names->name, r);
342         }
343         if (compare <= 0) {
344           break;
345         }
346       }
347       list_add_head(node, &names->node);
348     }
349 
350     /* Remove any file fragments that match our sequence number */
351     list_for_each_safe(node, n, &names->content) {
352       content = node_to_item(node, struct content, node);
353       if (log_msg.entry.nsec == content->entry.nsec) {
354         list_remove(&content->node);
355         free(content);
356       }
357     }
358 
359     /* Add content */
360     content = static_cast<struct content*>(
361         calloc(1, sizeof(content->node) + hdr_size + log_msg.entry.len));
362     if (!content) {
363       ret = -ENOMEM;
364       break;
365     }
366     memcpy(&content->entry, &log_msg.entry, hdr_size + log_msg.entry.len);
367 
368     /* Insert in sequence number sorted order, to ease reconstruction */
369     list_for_each_reverse(node, &names->content) {
370       if ((node_to_item(node, struct content, node))->entry.nsec < log_msg.entry.nsec) {
371         break;
372       }
373     }
374     list_add_head(node, &content->node);
375   }
376   PmsgClose(&logger_list);
377 
378   /* Progress through all the collected files */
379   list_for_each_safe(node, n, &name_list) {
380     struct listnode *content_node, *m;
381     char* buf;
382     size_t sequence, tag_len;
383 
384     names = node_to_item(node, struct names, node);
385 
386     /* Construct content into a linear buffer */
387     buf = NULL;
388     len = 0;
389     sequence = 0;
390     tag_len = strlen(names->name) + sizeof(char); /* tag + nul */
391     list_for_each_safe(content_node, m, &names->content) {
392       ssize_t add_len;
393 
394       content = node_to_item(content_node, struct content, node);
395       add_len = content->entry.len - tag_len - sizeof(prio);
396       if (add_len <= 0) {
397         list_remove(content_node);
398         free(content);
399         continue;
400       }
401 
402       if (!buf) {
403         buf = static_cast<char*>(malloc(sizeof(char)));
404         if (!buf) {
405           ret = -ENOMEM;
406           list_remove(content_node);
407           free(content);
408           continue;
409         }
410         *buf = '\0';
411       }
412 
413       /* Missing sequence numbers */
414       while (sequence < content->entry.nsec) {
415         /* plus space for enforced nul */
416         buf = static_cast<char*>(realloc_or_free(buf, len + sizeof(char) + sizeof(char)));
417         if (!buf) {
418           break;
419         }
420         buf[len] = '\f'; /* Mark missing content with a form feed */
421         buf[++len] = '\0';
422         sequence += ANDROID_LOG_PMSG_FILE_SEQUENCE;
423       }
424       if (!buf) {
425         ret = -ENOMEM;
426         list_remove(content_node);
427         free(content);
428         continue;
429       }
430       /* plus space for enforced nul */
431       buf = static_cast<char*>(realloc_or_free(buf, len + add_len + sizeof(char)));
432       if (!buf) {
433         ret = -ENOMEM;
434         list_remove(content_node);
435         free(content);
436         continue;
437       }
438       memcpy(buf + len, (char*)&content->entry + content->entry.hdr_size + tag_len + sizeof(prio),
439              add_len);
440       len += add_len;
441       buf[len] = '\0'; /* enforce trailing hidden nul */
442       sequence = content->entry.nsec + ANDROID_LOG_PMSG_FILE_SEQUENCE;
443 
444       list_remove(content_node);
445       free(content);
446     }
447     if (buf) {
448       if (len) {
449         /* Buffer contains enforced trailing nul just beyond length */
450         ssize_t r;
451         *strchr(names->name, ':') = '/'; /* Convert back to filename */
452         r = (*fn)(names->id, names->prio, names->name, buf, len, arg);
453         if ((ret >= 0) && (r > 0)) {
454           if (ret == SSIZE_MAX) {
455             ret = r;
456           } else {
457             ret += r;
458           }
459         } else if (r < ret) {
460           ret = r;
461         }
462       }
463       free(buf);
464     }
465     list_remove(node);
466     free(names);
467   }
468   return (ret == SSIZE_MAX) ? -ENOENT : ret;
469 }
470