summaryrefslogtreecommitdiffstats
path: root/utils/hwstub/tools/hwstub_load.cpp
blob: 6ca607929471d82fe0f6fb351e758d8ec20378b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * Copyright (C) 2013 by Amaury Pouly
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <stdbool.h>
#include <ctype.h>
#include <iostream>
#include "hwstub.hpp"
#include "hwstub_uri.hpp"

using namespace hwstub;

struct player_info_t
{
    const char *name;
    const char *username;
    int modelnum;
};

enum image_type_t
{
    IT_RAW,
    IT_ROCKBOX,
    IT_DETECT,
    /* positive values reserved for rockbox-specific models */
};

struct player_info_t players[] =
{
    { "zenv", "Zen V", 85 },
    { "zmoz", "Zen Mozaic", 87 },
    { "zen", "Zen", 90 },
    { "zxfi", "Zen X-Fi", 86 },
    { NULL, 0 },
};

enum image_type_t detect_type(unsigned char *buffer, size_t size)
{
    if(size < 8)
        return IT_RAW;
    int player;
    for(player = 0; players[player].name; player++)
        if(memcmp(buffer + 4, players[player].name, 4) == 0)
            break;
    if(players[player].name == NULL)
        return IT_RAW;
    unsigned long checksum = players[player].modelnum;
    for(size_t i = 8; i < size; i++)
        checksum += buffer[i];
    unsigned long expected = buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3];
    if(checksum != expected)
        return IT_RAW;
    return IT_ROCKBOX;
}

const char *get_player_name(unsigned char *buffer)
{
    for(int player = 0; players[player].name; player++)
        if(memcmp(buffer, players[player].name, 4) == 0)
            return players[player].username;
    return NULL;
}

bool could_be_rockbox(unsigned char *buffer, size_t size)
{
    /* usually target use 3 or 4 digits */
    if(size >= 8 && isprint(buffer[4]) && isprint(buffer[5]) && isprint(buffer[6]) &&
        (isprint(buffer[7]) || buffer[7] == 0))
    {
        unsigned long checksum = 0;
        for(size_t i = 8; i < size; i++)
            checksum += buffer[i];
        unsigned long expected = buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3];
        unsigned long expected_modelnm = expected - checksum;
        if(expected_modelnm < 150)
            fprintf(stderr, "This file looks like a valid rockbox image but I don't know this player: %.4s (modelnum=%ld)\n",
                buffer + 4, expected_modelnm);
        else
            fprintf(stderr, "This file could be a valid rockbox image but I don't know this player and the checksum is strange: %.4s\n",
                buffer + 4);
        return true;
    }
    else
        return false;
}

void usage(void)
{
    printf("usage: hwstub::load [options] <addr> <file>\n");
    printf("options:\n");
    printf("  --help/-?       Display this help\n");
    printf("  --quiet/-q      Quiet output\n");
    printf("  --type/-t <t>   Override file type\n");
    printf("  --dev/-d <uri>  Device URI (see below)\n");
    printf("  --verbose/-v    Display debug output\n");
    printf("file types:\n");
    printf("  raw      Load a raw binary blob\n");
    printf("  rockbox  Load a rockbox image produced by scramble\n");
    printf("  detect   Try to guess the format\n");
    printf("known players:");
    for(int i = 0; players[i].name; i++)
        printf(" %s", players[i].name);
    printf("\n");
    //hwstub::usage_uri(stdout);
    exit(1);
}

int main(int argc, char **argv)
{
    bool quiet = false;
    enum image_type_t type = IT_DETECT;
    const char *uri = "usb:";
    bool verbose = false;

    // parse command line
    while(1)
    {
        static struct option long_options[] =
        {
            {"help", no_argument, 0, '?'},
            {"quiet", no_argument, 0, 'q'},
            {"type", required_argument, 0, 't'},
            {"dev", required_argument, 0, 'd'},
            {"verbose", no_argument, 0, 'v'},
            {0, 0, 0, 0}
        };

        int c = getopt_long(argc, argv, "?qt:d:v", long_options, NULL);
        if(c == -1)
            break;
        switch(c)
        {
            case -1:
                break;
            case 'q':
                quiet = true;
                break;
            case '?':
                usage();
                break;
            case 't':
                if(strcmp(optarg, "raw") == 0)
                    type = IT_RAW;
                else if(strcmp(optarg, "rockbox") == 0)
                    type = IT_ROCKBOX;
                else if(strcmp(optarg, "detect") == 0)
                    type = IT_DETECT;
                else
                {
                    fprintf(stderr, "Unknown file type '%s'\n", optarg);
                    return 1;
                }
                break;
            case 'd':
                uri = optarg;
                break;
            case 'v':
                verbose = true;
                break;
            default:
                abort();
        }
    }

    if(optind + 2 != argc)
        usage();

    char *end;
    unsigned long addr = strtoul(argv[optind], &end, 0);
    if(*end)
    {
        fprintf(stderr, "Invalid load address\n");
        return 2;
    }

    FILE *f = fopen(argv[optind + 1], "rb");
    if(f == NULL)
    {
        fprintf(stderr, "Cannot open file for reading: %m\n");
        return 3;
    }
    fseek(f, 0, SEEK_END);
    size_t size = ftell(f);
    fseek(f, 0, SEEK_SET);
    unsigned char *buffer = (unsigned char*)malloc(size);
    fread(buffer, size, 1, f);
    fclose(f);

    if(type == IT_ROCKBOX || type == IT_DETECT)
    {
        enum image_type_t det = detect_type(buffer, size);
        if(type == IT_ROCKBOX && det != IT_ROCKBOX)
        {
            if(!could_be_rockbox(buffer, size))
                fprintf(stderr, "This file does not appear to be valid rockbox image.\n");
            return 4;
        }
        if(type == IT_DETECT && det == IT_RAW)
            could_be_rockbox(buffer, size);
        type = det;
        if(type == IT_ROCKBOX)
        {
            if(!quiet)
                printf("Rockox image is for player %s (%.4s)\n", get_player_name(buffer + 4), buffer + 4);
            memmove(buffer, buffer + 8, size - 8);
            size -= 8;
        }
    }

    if(!quiet)
    {
        if(type == IT_RAW)
            printf("Loading raw image at %#lx\n", addr);
        else
            printf("Loading rockbox image at %#lx\n", addr);
    }

    // create usb context
    std::string errstr;
    std::shared_ptr<context> hwctx = uri::create_context(uri::uri(uri), &errstr);
    if(!hwctx)
    {
        printf("Cannot create context: %s\n", errstr.c_str());
        return 1;
    }
    if(verbose)
        hwctx->set_debug(std::cout);
    std::vector<std::shared_ptr<hwstub::device>> list;
    hwstub::error ret = hwctx->get_device_list(list);
    if(ret != hwstub::error::SUCCESS)
    {
        printf("Cannot get device list: %d\n", (int)ret);
        return 1;
    }
    if(list.size() == 0)
    {
        printf("No hwstub device detected!\n");
        return 1;
    }
    /* open first device */
    std::shared_ptr<hwstub::handle> hwdev;
    ret = list[0]->open(hwdev);
    if(ret != hwstub::error::SUCCESS)
    {
        printf("Cannot open device: %d\n", (int)ret);
        return 1;
    }

    size_t out_size = size;
    ret = hwdev->write(addr, buffer, out_size, false);
    if(ret != hwstub::error::SUCCESS || out_size != size)
    {
        fprintf(stderr, "Image write failed: %s, %zu/%zu\n", error_string(ret).c_str(),
            out_size, size);
        goto Lerr;
    }
    hwdev->exec(addr, HWSTUB_EXEC_JUMP);

    return 0;

    Lerr:
    // display log if handled
    fprintf(stderr, "Device log:\n");
    do
    {
        char buffer[128];
        size_t size = sizeof(buffer) - 1;
        hwstub::error err = hwdev->get_log(buffer, size);
        if(err != error::SUCCESS || size == 0)
            break;
        buffer[size] = 0;
        fprintf(stderr, "%s", buffer);
    }while(1);
    return 1;
}