• 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   logger_list.log_mask = (1 << logId);
189   logger_list.log_mask &= ~((1 << LOG_ID_KERNEL) | (1 << LOG_ID_EVENTS) | (1 << LOG_ID_SECURITY));
190   if (!logger_list.log_mask) {
191     return -EINVAL;
192   }
193 
194   /* Initialize name list */
195   list_init(&name_list);
196 
197   ret = SSIZE_MAX;
198 
199   /* Validate incoming prefix, shift until it contains only 0 or 1 : or / */
200   prefix_len = 0;
201   if (prefix) {
202     const char *prev = NULL, *last = NULL, *cp = prefix;
203     while ((cp = strpbrk(cp, "/:"))) {
204       prev = last;
205       last = cp;
206       cp = cp + 1;
207     }
208     if (prev) {
209       prefix = prev + 1;
210     }
211     prefix_len = strlen(prefix);
212   }
213 
214   /* Read the file content */
215   log_msg log_msg;
216   while (PmsgRead(&logger_list, &log_msg) > 0) {
217     const char* cp;
218     size_t hdr_size = log_msg.entry.hdr_size;
219 
220     char* msg = (char*)&log_msg + hdr_size;
221     const char* split = NULL;
222 
223     if (hdr_size != sizeof(log_msg.entry)) {
224       continue;
225     }
226     /* Check for invalid sequence number */
227     if (log_msg.entry.nsec % ANDROID_LOG_PMSG_FILE_SEQUENCE ||
228         (log_msg.entry.nsec / ANDROID_LOG_PMSG_FILE_SEQUENCE) >=
229             ANDROID_LOG_PMSG_FILE_MAX_SEQUENCE) {
230       continue;
231     }
232 
233     /* Determine if it has <dirbase>:<filebase> format for tag */
234     len = log_msg.entry.len - sizeof(prio);
235     for (cp = msg + sizeof(prio); *cp && isprint(*cp) && !isspace(*cp) && --len; ++cp) {
236       if (*cp == ':') {
237         if (split) {
238           break;
239         }
240         split = cp;
241       }
242     }
243     if (*cp || !split) {
244       continue;
245     }
246 
247     /* Filters */
248     if (prefix_len && strncmp(msg + sizeof(prio), prefix, prefix_len)) {
249       size_t offset;
250       /*
251        *   Allow : to be a synonym for /
252        * Things we do dealing with const char * and do not alloc
253        */
254       split = strchr(prefix, ':');
255       if (split) {
256         continue;
257       }
258       split = strchr(prefix, '/');
259       if (!split) {
260         continue;
261       }
262       offset = split - prefix;
263       if ((msg[offset + sizeof(prio)] != ':') || strncmp(msg + sizeof(prio), prefix, offset)) {
264         continue;
265       }
266       ++offset;
267       if ((prefix_len > offset) &&
268           strncmp(&msg[offset + sizeof(prio)], split + 1, prefix_len - offset)) {
269         continue;
270       }
271     }
272 
273     if ((prio != ANDROID_LOG_ANY) && (*msg < prio)) {
274       continue;
275     }
276 
277     /* check if there is an existing entry */
278     list_for_each(node, &name_list) {
279       names = node_to_item(node, struct names, node);
280       if (!strcmp(names->name, msg + sizeof(prio)) && names->id == log_msg.entry.lid &&
281           names->prio == *msg) {
282         break;
283       }
284     }
285 
286     /* We do not have an existing entry, create and add one */
287     if (node == &name_list) {
288       static const char numbers[] = "0123456789";
289       unsigned long long nl;
290 
291       len = strlen(msg + sizeof(prio)) + 1;
292       names = static_cast<struct names*>(calloc(1, sizeof(*names) + len));
293       if (!names) {
294         ret = -ENOMEM;
295         break;
296       }
297       strcpy(names->name, msg + sizeof(prio));
298       names->id = static_cast<log_id_t>(log_msg.entry.lid);
299       names->prio = *msg;
300       list_init(&names->content);
301       /*
302        * Insert in reverse numeric _then_ alpha sorted order as
303        * representative of log rotation:
304        *
305        *   log.10
306        *   klog.10
307        *   . . .
308        *   log.2
309        *   klog.2
310        *   log.1
311        *   klog.1
312        *   log
313        *   klog
314        *
315        * thus when we present the content, we are provided the oldest
316        * first, which when 'refreshed' could spill off the end of the
317        * pmsg FIFO but retaining the newest data for last with best
318        * chances to survive.
319        */
320       nl = 0;
321       cp = strpbrk(names->name, numbers);
322       if (cp) {
323         nl = strtoull(cp, NULL, 10);
324       }
325       list_for_each_reverse(node, &name_list) {
326         struct names* a_name = node_to_item(node, struct names, node);
327         const char* r = a_name->name;
328         int compare = 0;
329 
330         unsigned long long nr = 0;
331         cp = strpbrk(r, numbers);
332         if (cp) {
333           nr = strtoull(cp, NULL, 10);
334         }
335         if (nr != nl) {
336           compare = (nl > nr) ? 1 : -1;
337         }
338         if (compare == 0) {
339           compare = strcmp(names->name, r);
340         }
341         if (compare <= 0) {
342           break;
343         }
344       }
345       list_add_head(node, &names->node);
346     }
347 
348     /* Remove any file fragments that match our sequence number */
349     list_for_each_safe(node, n, &names->content) {
350       content = node_to_item(node, struct content, node);
351       if (log_msg.entry.nsec == content->entry.nsec) {
352         list_remove(&content->node);
353         free(content);
354       }
355     }
356 
357     /* Add content */
358     content = static_cast<struct content*>(
359         calloc(1, sizeof(content->node) + hdr_size + log_msg.entry.len));
360     if (!content) {
361       ret = -ENOMEM;
362       break;
363     }
364     memcpy(&content->entry, &log_msg.entry, hdr_size + log_msg.entry.len);
365 
366     /* Insert in sequence number sorted order, to ease reconstruction */
367     list_for_each_reverse(node, &names->content) {
368       if ((node_to_item(node, struct content, node))->entry.nsec < log_msg.entry.nsec) {
369         break;
370       }
371     }
372     list_add_head(node, &content->node);
373   }
374   PmsgClose(&logger_list);
375 
376   /* Progress through all the collected files */
377   list_for_each_safe(node, n, &name_list) {
378     struct listnode *content_node, *m;
379     char* buf;
380     size_t sequence, tag_len;
381 
382     names = node_to_item(node, struct names, node);
383 
384     /* Construct content into a linear buffer */
385     buf = NULL;
386     len = 0;
387     sequence = 0;
388     tag_len = strlen(names->name) + sizeof(char); /* tag + nul */
389     list_for_each_safe(content_node, m, &names->content) {
390       ssize_t add_len;
391 
392       content = node_to_item(content_node, struct content, node);
393       add_len = content->entry.len - tag_len - sizeof(prio);
394       if (add_len <= 0) {
395         list_remove(content_node);
396         free(content);
397         continue;
398       }
399 
400       if (!buf) {
401         buf = static_cast<char*>(malloc(sizeof(char)));
402         if (!buf) {
403           ret = -ENOMEM;
404           list_remove(content_node);
405           free(content);
406           continue;
407         }
408         *buf = '\0';
409       }
410 
411       /* Missing sequence numbers */
412       while (sequence < content->entry.nsec) {
413         /* plus space for enforced nul */
414         buf = static_cast<char*>(realloc_or_free(buf, len + sizeof(char) + sizeof(char)));
415         if (!buf) {
416           break;
417         }
418         buf[len] = '\f'; /* Mark missing content with a form feed */
419         buf[++len] = '\0';
420         sequence += ANDROID_LOG_PMSG_FILE_SEQUENCE;
421       }
422       if (!buf) {
423         ret = -ENOMEM;
424         list_remove(content_node);
425         free(content);
426         continue;
427       }
428       /* plus space for enforced nul */
429       buf = static_cast<char*>(realloc_or_free(buf, len + add_len + sizeof(char)));
430       if (!buf) {
431         ret = -ENOMEM;
432         list_remove(content_node);
433         free(content);
434         continue;
435       }
436       memcpy(buf + len, (char*)&content->entry + content->entry.hdr_size + tag_len + sizeof(prio),
437              add_len);
438       len += add_len;
439       buf[len] = '\0'; /* enforce trailing hidden nul */
440       sequence = content->entry.nsec + ANDROID_LOG_PMSG_FILE_SEQUENCE;
441 
442       list_remove(content_node);
443       free(content);
444     }
445     if (buf) {
446       if (len) {
447         /* Buffer contains enforced trailing nul just beyond length */
448         ssize_t r;
449         *strchr(names->name, ':') = '/'; /* Convert back to filename */
450         r = (*fn)(names->id, names->prio, names->name, buf, len, arg);
451         if ((ret >= 0) && (r > 0)) {
452           if (ret == SSIZE_MAX) {
453             ret = r;
454           } else {
455             ret += r;
456           }
457         } else if (r < ret) {
458           ret = r;
459         }
460       }
461       free(buf);
462     }
463     list_remove(node);
464     free(names);
465   }
466   return (ret == SSIZE_MAX) ? -ENOENT : ret;
467 }
468