Home | History | Annotate | Download | only in android
      1 /*
      2  * Copyright (C) 2010 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 /* Limited driver for the Qcow2 filesystem, capable of extracting snapshot
     18  * metadata from Qcow2 formatted image file.
     19  *
     20  * Similar functionality is implemented in block/qcow2.c, block/qcow2-snapshot.c
     21  * and block.c. This separate implementation was made to further decouple the UI
     22  * of the Android emulator from the underlying Qemu system. It allows the UI to
     23  * show snapshot listings without having to fall back on Qemu's block driver
     24  * system, which would pull in a lot of code irrelevant for the UI.
     25  */
     26 
     27 #include <errno.h>
     28 #include <fcntl.h>
     29 #include <stdint.h>
     30 #include <stdio.h>
     31 #include <stdlib.h>
     32 #include <string.h>
     33 #include <time.h>
     34 #include <unistd.h>
     35 
     36 #include "qemu/bswap.h"
     37 #include "android/utils/debug.h"
     38 #include "android/utils/eintr_wrapper.h"
     39 #include "android/utils/system.h"
     40 #include "android/snapshot.h"
     41 
     42 /* "Magic" sequence of four bytes required by spec to be the first four bytes
     43  * of any Qcow file.
     44  */
     45 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
     46 #define QCOW_VERSION 2
     47 
     48 /* Reads 'nbyte' bytes from 'fd' into 'buf', retrying on interrupts.
     49  * Exit()s if the read fails for any other reason.
     50  */
     51 static int
     52 read_or_die(int fd, void *buf, size_t nbyte)
     53 {
     54     int ret = HANDLE_EINTR(read(fd, buf, nbyte));
     55     if (ret < 0) {
     56         derror("read failed: %s", strerror(errno));
     57         exit(1);
     58     }
     59     return ret;
     60 }
     61 
     62 /* Wrapper around lseek(), exit()s on error.
     63  */
     64 static off_t
     65 seek_or_die(int fd, off_t offset, int whence)
     66 {
     67     off_t ret = lseek(fd, offset, whence);
     68     if (ret < 0) {
     69         derror("seek failed: %s", strerror(errno));
     70         exit(1);
     71     }
     72     return ret;
     73 }
     74 
     75 
     76 typedef struct SnapshotInfo {
     77     char *id_str;
     78     char *name;
     79 
     80     uint32_t date_sec;
     81     uint32_t date_nsec;
     82 
     83     uint64_t vm_clock_nsec;
     84     uint32_t vm_state_size;
     85 } SnapshotInfo;
     86 
     87 static SnapshotInfo*
     88 snapshot_info_alloc()
     89 {
     90     return android_alloc(sizeof(SnapshotInfo));
     91 }
     92 
     93 static void
     94 snapshot_info_free( SnapshotInfo* info )
     95 {
     96     AFREE(info->id_str);
     97     AFREE(info->name);
     98     AFREE(info);
     99 }
    100 
    101 
    102 /* Reads a snapshot record from a qcow2-formatted file.
    103  *
    104  * The function assumes the file position of 'fd' points to the beginning of a
    105  * QcowSnapshotHeader record. When the call returns, the file position of fd is
    106  * at the place where the next QcowSnapshotHeader should start, if there is one.
    107  *
    108  * C.f. QCowSnapshotHeader in block/qcow2-snapshot.c for the complete layout of
    109  * the header.
    110  */
    111 static void
    112 snapshot_info_read( int fd, SnapshotInfo* info )
    113 {
    114     uint64_t start_offset = seek_or_die(fd, 0, SEEK_CUR);
    115 
    116     uint32_t extra_data_size;
    117     uint16_t id_str_size, name_size;
    118 
    119     /* read fixed-length fields */
    120     seek_or_die(fd, 12, SEEK_CUR);  /* skip l1 info */
    121     read_or_die(fd, &id_str_size,         sizeof(id_str_size));
    122     read_or_die(fd, &name_size,           sizeof(name_size));
    123     read_or_die(fd, &info->date_sec,      sizeof(info->date_sec));
    124     read_or_die(fd, &info->date_nsec,     sizeof(info->date_nsec));
    125     read_or_die(fd, &info->vm_clock_nsec, sizeof(info->vm_clock_nsec));
    126     read_or_die(fd, &info->vm_state_size, sizeof(info->vm_state_size));
    127     read_or_die(fd, &extra_data_size,     sizeof(extra_data_size));
    128 
    129     /* convert to host endianness */
    130     be16_to_cpus(&id_str_size);
    131     be16_to_cpus(&name_size);
    132     be32_to_cpus(&info->date_sec);
    133     be32_to_cpus(&info->date_nsec);
    134     be64_to_cpus(&info->vm_clock_nsec);
    135     be32_to_cpus(&info->vm_state_size);
    136     be32_to_cpus(&extra_data_size);
    137     be32_to_cpus(&extra_data_size);
    138 
    139     /* read variable-length buffers*/
    140     info->id_str = android_alloc(id_str_size + 1); // +1: manual null-termination
    141     info->name   = android_alloc(name_size + 1);
    142     seek_or_die(fd, extra_data_size, SEEK_CUR);  /* skip extra data */
    143     read_or_die(fd, info->id_str, id_str_size);
    144     read_or_die(fd, info->name, name_size);
    145 
    146     info->id_str[id_str_size] = '\0';
    147     info->name[name_size] = '\0';
    148 
    149     /* headers are 8 byte aligned, ceil to nearest multiple of 8 */
    150     uint64_t end_offset   = seek_or_die(fd, 0, SEEK_CUR);
    151     uint32_t total_size   = end_offset - start_offset;
    152     uint32_t aligned_size = ((total_size - 1) / 8 + 1) * 8;
    153 
    154     /* skip to start of next record */
    155     seek_or_die(fd, start_offset + aligned_size, SEEK_SET);
    156 }
    157 
    158 
    159 #define NB_SUFFIXES 4
    160 
    161 /* Returns the size of a snapshot in a human-readable format.
    162  *
    163  * This function copyright (c) 2003 Fabrice Bellard
    164  */
    165 static char*
    166 snapshot_format_size( char *buf, int buf_size, int64_t size )
    167 {
    168     static const char suffixes[NB_SUFFIXES] = "KMGT";
    169     int64_t base;
    170     int i;
    171 
    172     if (size <= 999) {
    173         snprintf(buf, buf_size, "%" PRId64, size);
    174     } else {
    175         base = 1024;
    176         for(i = 0; i < NB_SUFFIXES; i++) {
    177             if (size < (10 * base)) {
    178                 snprintf(buf, buf_size, "%0.1f%c",
    179                          (double)size / base,
    180                          suffixes[i]);
    181                 break;
    182             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
    183                 snprintf(buf, buf_size, "%" PRId64 "%c",
    184                          ((size + (base >> 1)) / base),
    185                          suffixes[i]);
    186                 break;
    187             }
    188             base = base * 1024;
    189         }
    190     }
    191     return buf;
    192 }
    193 
    194 static char*
    195 snapshot_format_create_date( char *buf, size_t buf_size, time_t *time )
    196 {
    197     struct tm *tm;
    198     tm = localtime(time);
    199     if (!tm) {
    200         snprintf(buf, buf_size, "<invalid-snapshot-date>");
    201     } else {
    202         strftime(buf, buf_size, "%Y-%m-%d %H:%M:%S", tm);
    203     }
    204     return buf;
    205 }
    206 
    207 static char*
    208 snapshot_format_vm_clock( char *buf, size_t buf_size, uint64_t vm_clock_nsec )
    209 {
    210     uint64_t secs = vm_clock_nsec / 1000000000;
    211     snprintf(buf, buf_size, "%02d:%02d:%02d.%03d",
    212                             (int)(secs / 3600),
    213                             (int)((secs / 60) % 60),
    214                             (int)(secs % 60),
    215                             (int)((vm_clock_nsec / 1000000) % 1000));
    216     return buf;
    217 }
    218 
    219 /* Prints a row of the snapshot table to stdout. */
    220 static void
    221 snapshot_info_print( SnapshotInfo *info )
    222 {
    223     char size_buf[8];
    224     char date_buf[21];
    225     char clock_buf[21];
    226 
    227     // Note: time_t might be larger than uint32_t.
    228     time_t date_sec = info->date_sec;
    229 
    230     snapshot_format_size(size_buf, sizeof(size_buf), info->vm_state_size);
    231     snapshot_format_create_date(date_buf, sizeof(date_buf), &date_sec);
    232     snapshot_format_vm_clock(clock_buf, sizeof(clock_buf), info->vm_clock_nsec);
    233 
    234     printf(" %-10s%-20s%7s%20s%15s\n",
    235            info->id_str, info->name, size_buf, date_buf, clock_buf);
    236 }
    237 
    238 /* Prints table of all snapshots recorded in the file 'fd'.
    239  */
    240 static void
    241 snapshot_print_table( int fd, uint32_t nb_snapshots, uint64_t snapshots_offset )
    242 {
    243     printf(" %-10s%-20s%7s%20s%15s\n",
    244            "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
    245 
    246     /* skip ahead to snapshot data */
    247     seek_or_die(fd, snapshots_offset, SEEK_SET);
    248 
    249     /* iterate over snapshot records */
    250     int i;
    251     for (i = 0; i < nb_snapshots; i++) {
    252         SnapshotInfo *info = snapshot_info_alloc();
    253         snapshot_info_read(fd, info);
    254         snapshot_info_print(info);
    255 
    256         snapshot_info_free(info);
    257     }
    258 }
    259 
    260 /* Validates that 'fd' starts with a correct Qcow 2 header. Prints an error and
    261  * exit()s if validation fails.
    262  */
    263 static void
    264 snapshot_validate_qcow_file( int fd )
    265 {
    266     /* read magic number and qcow version (2x4 bytes) */
    267     uint32_t magic, version;
    268     read_or_die(fd, &magic, sizeof(magic));
    269     read_or_die(fd, &version, sizeof(version));
    270     be32_to_cpus(&magic);
    271     be32_to_cpus(&version);
    272 
    273     if (magic != QCOW_MAGIC) {
    274         derror("Not a valid Qcow snapshot file (expected magic value '%08x', got '%08x').",
    275                QCOW_MAGIC, magic);
    276         exit(1);
    277     }
    278     if (version != QCOW_VERSION) {
    279         derror("Unsupported Qcow version (need %d, got %d).",
    280                QCOW_VERSION, version);
    281         exit(1);
    282     }
    283 }
    284 
    285 /* Reads snapshot information from a Qcow2 file header.
    286  *
    287  * C.f. QCowHeader in block/qcow2.h for an exact listing of the header
    288  * contents.
    289  */
    290 static void
    291 snapshot_read_qcow_header( int fd, uint32_t *nb_snapshots, uint64_t *snapshots_offset )
    292 {
    293     snapshot_validate_qcow_file(fd);
    294 
    295     /* skip non-snapshot related metadata (4x8 + 5x4 = 52 bytes)*/
    296     seek_or_die(fd, 52, SEEK_CUR);
    297 
    298     read_or_die(fd, nb_snapshots, sizeof(*nb_snapshots));
    299     read_or_die(fd, snapshots_offset, sizeof(*snapshots_offset));
    300 
    301     /* convert to host endianness */
    302     be32_to_cpus(nb_snapshots);
    303     be64_to_cpus(snapshots_offset);
    304 }
    305 
    306 /* Prints a table with information on the snapshots in the qcow2-formatted file
    307  * 'snapstorage', then exit()s.
    308  */
    309 void
    310 snapshot_print_and_exit( const char *snapstorage )
    311 {
    312     /* open snapshot file */
    313     int fd = open(snapstorage, O_RDONLY);
    314     if (fd < 0) {
    315         derror("Could not open snapshot file '%s': %s", snapstorage, strerror(errno));
    316         exit(1);
    317     }
    318 
    319     /* read snapshot info from file header */
    320     uint32_t nb_snapshots;
    321     uint64_t snapshots_offset;
    322     snapshot_read_qcow_header(fd, &nb_snapshots, &snapshots_offset);
    323 
    324     if (nb_snapshots > 0) {
    325         printf("Snapshots in file '%s':\n", snapstorage);
    326         snapshot_print_table(fd, nb_snapshots, snapshots_offset);
    327     }
    328     else {
    329         printf("File '%s' contains no snapshots yet.\n", snapstorage);
    330     }
    331 
    332     close(fd);
    333     exit(0);
    334 }
    335