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