]> sigrok.org Git - libsigrok.git/blob - input/vcd.c
Improve compatibility with various kinds of VCD files.
[libsigrok.git] / input / vcd.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2012 Petteri Aimonen <jpa@sr.mail.kapsi.fi>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /* The VCD input module has the following options:
21  *
22  * numprobes:   Maximum number of probes to use. The probes are
23  *              detected in the same order as they are listed
24  *              in the $var sections of the VCD file.
25  *
26  * skip:        Allows skipping until given timestamp in the file.
27  *              This can speed up analyzing of long captures.
28  *            
29  *              Value < 0: Skip until first timestamp listed in
30  *              the file. (default)
31  *
32  *              Value = 0: Do not skip, instead generate samples
33  *              beginning from timestamp 0.
34  *
35  *              Value > 0: Start at the given timestamp.
36  *
37  * downsample:  Divide the samplerate by the given factor.
38  *              This can speed up analyzing of long captures.
39  *
40  * Based on Verilog standard IEEE Std 1364-2001 Version C
41  *
42  * Supported features:
43  * - $var with 'wire' and 'reg' types of scalar variables
44  * - $timescale definition for samplerate
45  * - multiple character variable identifiers
46  *
47  * Most important unsupported features:
48  * - vector variables (bit vectors etc.)
49  * - analog, integer and real number variables
50  * - $dumpvars initial value declaration
51  * - $scope namespaces
52  */
53
54 /*  */
55
56 #include <stdlib.h>
57 #include <glib.h>
58 #include <stdio.h>
59 #include <string.h>
60 #include "libsigrok.h"
61 #include "libsigrok-internal.h"
62
63 /* Message logging helpers with driver-specific prefix string. */
64 #define DRIVER_LOG_DOMAIN "input/vcd: "
65 #define sr_log(l, s, args...) sr_log(l, DRIVER_LOG_DOMAIN s, ## args)
66 #define sr_spew(s, args...) sr_spew(DRIVER_LOG_DOMAIN s, ## args)
67 #define sr_dbg(s, args...) sr_dbg(DRIVER_LOG_DOMAIN s, ## args)
68 #define sr_info(s, args...) sr_info(DRIVER_LOG_DOMAIN s, ## args)
69 #define sr_warn(s, args...) sr_warn(DRIVER_LOG_DOMAIN s, ## args)
70 #define sr_err(s, args...) sr_err(DRIVER_LOG_DOMAIN s, ## args)
71
72 #define DEFAULT_NUM_PROBES 8
73
74 /* Read until specific type of character occurs in file.
75  * Skip input if dest is NULL.
76  * Modes:
77  * 'W' read until whitespace
78  * 'N' read until non-whitespace, and ungetc() the character
79  * '$' read until $end
80  */
81 static gboolean read_until(FILE *file, GString *dest, char mode)
82 {
83         char prev[4] = "";
84         long startpos = ftell(file);
85         for(;;)
86         {
87                 int c = fgetc(file);
88
89                 if (c == EOF)
90                 {
91                         if (mode == '$')
92                                 sr_err("Unexpected EOF, read started at %ld.", startpos);
93                         return FALSE;
94                 }
95                 
96                 if (mode == 'W' && g_ascii_isspace(c))
97                         return TRUE;
98                 
99                 if (mode == 'N' && !g_ascii_isspace(c))
100                 {
101                         ungetc(c, file);
102                         return TRUE;
103                 }
104                 
105                 if (mode == '$')
106                 {
107                         prev[0] = prev[1]; prev[1] = prev[2]; prev[2] = prev[3]; prev[3] = c;
108                         if (prev[0] == '$' && prev[1] == 'e' && prev[2] == 'n' && prev[3] == 'd')
109                         {
110                                 if (dest != NULL)
111                                         g_string_truncate(dest, dest->len - 3);
112                                         
113                                 return TRUE;
114                         }
115                 }
116
117                 if (dest != NULL)
118                         g_string_append_c(dest, c);
119         }
120 }
121
122 /* Reads a single VCD section from input file and parses it to structure.
123  * e.g. $timescale 1ps $end  => "timescale" "1ps"
124  */
125 static gboolean parse_section(FILE *file, gchar **name, gchar **contents)
126 {
127         gboolean status;
128         GString *sname, *scontents;
129         
130         /* Skip any initial white-space */
131         if (!read_until(file, NULL, 'N')) return FALSE;
132         
133         /* Section tag should start with $. */
134         if (fgetc(file) != '$')
135         {
136                 sr_err("Expected $ at beginning of section.");
137                 return FALSE;
138         }
139         
140         /* Read the section tag */      
141         sname = g_string_sized_new(32);
142         status = read_until(file, sname, 'W');
143         
144         /* Skip whitespace before content */
145         status = status && read_until(file, NULL, 'N');
146         
147         /* Read the content */
148         scontents = g_string_sized_new(128);
149         status = status && read_until(file, scontents, '$');
150         g_strchomp(scontents->str);
151
152         /* Release strings if status is FALSE, return them if status is TRUE */ 
153         *name = g_string_free(sname, !status);
154         *contents = g_string_free(scontents, !status);
155         return status;
156 }
157
158 struct probe
159 {
160         gchar *name;
161         gchar *identifier;
162 };
163
164 struct context
165 {
166         uint64_t samplerate;
167         int maxprobes;
168         int probecount;
169         int downsample;
170         int64_t skip;
171         struct probe probes[SR_MAX_NUM_PROBES];
172 };
173
174 static void release_context(struct context *ctx)
175 {
176         int i;
177         for (i = 0; i < ctx->probecount; i++)
178         {
179                 g_free(ctx->probes[i].name); ctx->probes[i].name = NULL;
180                 g_free(ctx->probes[i].identifier); ctx->probes[i].identifier = NULL;
181         }
182         
183         g_free(ctx);
184 }
185
186 /* Remove empty parts from an array returned by g_strsplit. */
187 static void remove_empty_parts(gchar **parts)
188 {
189         gchar **src = parts;
190         gchar **dest = parts;
191         while (*src != NULL)
192         {
193                 if (**src != '\0')
194                 {
195                         *dest++ = *src;
196                 }
197                 
198                 src++;
199         }
200         
201         *dest = NULL;
202 }
203
204 /* Parse VCD header to get values for context structure.
205  * The context structure should be zeroed before calling this.
206  */
207 static gboolean parse_header(FILE *file, struct context *ctx)
208 {
209         gchar *name = NULL, *contents = NULL;
210         gboolean status = FALSE;
211
212         while (parse_section(file, &name, &contents))
213         {
214                 sr_dbg("Section '%s', contents '%s'.", name, contents);
215         
216                 if (g_strcmp0(name, "enddefinitions") == 0)
217                 {
218                         status = TRUE;
219                         break;
220                 }
221                 else if (g_strcmp0(name, "timescale") == 0)
222                 {
223                         /* The standard allows for values 1, 10 or 100
224                          * and units s, ms, us, ns, ps and fs. */
225                         struct sr_rational period;
226                         if (sr_parse_period(contents, &period) == SR_OK)
227                         {
228                                 ctx->samplerate = period.q / period.p;
229                                 if (period.q % period.p != 0)
230                                 {
231                                         /* Does not happen unless time value is non-standard */
232                                         sr_warn("Inexact rounding of samplerate, %" PRIu64 " / %" PRIu64 " to %" PRIu64 " Hz.",
233                                                 period.q, period.p, ctx->samplerate);
234                                 }
235                                 
236                                 sr_dbg("Samplerate: %" PRIu64, ctx->samplerate);
237                         }
238                         else
239                         {
240                                 sr_err("Parsing timescale failed.");
241                         }
242                 }
243                 else if (g_strcmp0(name, "var") == 0)
244                 {
245                         /* Format: $var type size identifier reference $end */
246                         gchar **parts = g_strsplit_set(contents, " \r\n\t", 0);
247                         remove_empty_parts(parts);
248                         
249                         if (g_strv_length(parts) != 4)
250                         {
251                                 sr_warn("$var section should have 4 items");
252                         }
253                         else if (g_strcmp0(parts[0], "reg") != 0 && g_strcmp0(parts[0], "wire") != 0)
254                         {
255                                 sr_info("Unsupported signal type: '%s'", parts[0]);
256                         }
257                         else if (strtol(parts[1], NULL, 10) != 1)
258                         {
259                                 sr_info("Unsupported signal size: '%s'", parts[1]);
260                         }
261                         else if (ctx->probecount >= ctx->maxprobes)
262                         {
263                                 sr_warn("Skipping '%s' because only %d probes requested.", parts[3], ctx->maxprobes);
264                         }
265                         else
266                         {
267                                 sr_info("Probe %d is '%s' identified by '%s'.", ctx->probecount, parts[3], parts[2]);
268                                 ctx->probes[ctx->probecount].identifier = g_strdup(parts[2]);
269                                 ctx->probes[ctx->probecount].name = g_strdup(parts[3]);
270                                 ctx->probecount++;
271                         }
272                         
273                         g_strfreev(parts);
274                 }
275                 
276                 g_free(name); name = NULL;
277                 g_free(contents); contents = NULL;
278         }
279         
280         g_free(name);
281         g_free(contents);
282         
283         return status;
284 }
285
286 static int format_match(const char *filename)
287 {
288         FILE *file;
289         gchar *name = NULL, *contents = NULL;
290         gboolean status;
291         
292         file = fopen(filename, "r");
293         if (file == NULL)
294                 return FALSE;
295
296         /* If we can parse the first section correctly,
297          * then it is assumed to be a VCD file.
298          */
299         status = parse_section(file, &name, &contents);
300         status = status && (*name != '\0');
301         
302         g_free(name);
303         g_free(contents);
304         fclose(file);
305         
306         return status;
307 }
308
309 static int init(struct sr_input *in)
310 {
311         struct sr_probe *probe;
312         int num_probes, i;
313         char name[SR_MAX_PROBENAME_LEN + 1];
314         char *param;
315         struct context *ctx;
316
317         if (!(ctx = g_try_malloc0(sizeof(*ctx)))) {
318                 sr_err("Input format context malloc failed.");
319                 return SR_ERR_MALLOC;
320         }
321
322         num_probes = DEFAULT_NUM_PROBES;
323         ctx->samplerate = 0;
324         ctx->downsample = 1;
325         ctx->skip = -1;
326
327         if (in->param) {
328                 param = g_hash_table_lookup(in->param, "numprobes");
329                 if (param) {
330                         num_probes = strtoul(param, NULL, 10);
331                         if (num_probes < 1)
332                         {
333                                 release_context(ctx);
334                                 return SR_ERR;
335                         }
336                 }
337                 
338                 param = g_hash_table_lookup(in->param, "downsample");
339                 if (param) {
340                         ctx->downsample = strtoul(param, NULL, 10);
341                         if (ctx->downsample < 1)
342                         {
343                                 ctx->downsample = 1;
344                         }
345                 }
346                 
347                 param = g_hash_table_lookup(in->param, "skip");
348                 if (param) {
349                         ctx->skip = strtoul(param, NULL, 10) / ctx->downsample;
350                 }
351         }
352         
353         /* Maximum number of probes to parse from the VCD */
354         ctx->maxprobes = num_probes;
355
356         /* Create a virtual device. */
357         in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
358         in->internal = ctx;
359
360         for (i = 0; i < num_probes; i++) {
361                 snprintf(name, SR_MAX_PROBENAME_LEN, "%d", i);
362                 
363                 if (!(probe = sr_probe_new(i, SR_PROBE_LOGIC, TRUE, name)))
364                 {
365                         release_context(ctx);
366                         return SR_ERR;
367                 }
368                         
369                 in->sdi->probes = g_slist_append(in->sdi->probes, probe);
370         }
371
372         return SR_OK;
373 }
374
375 #define CHUNKSIZE 1024
376
377 /* Send N samples of the given value. */
378 static void send_samples(const struct sr_dev_inst *sdi, uint64_t sample, uint64_t count)
379 {
380         struct sr_datafeed_packet packet;
381         struct sr_datafeed_logic logic;
382         uint64_t buffer[CHUNKSIZE];
383         uint64_t i;
384         unsigned chunksize = CHUNKSIZE;
385                 
386         if (count < chunksize)
387                 chunksize = count;
388
389         for (i = 0; i < chunksize; i++)
390         {
391                 buffer[i] = sample;
392         }
393         
394         packet.type = SR_DF_LOGIC;
395         packet.payload = &logic;        
396         logic.unitsize = sizeof(uint64_t);
397         logic.data = buffer;
398         
399         while (count)
400         {
401                 if (count < chunksize)
402                         chunksize = count;
403         
404                 logic.length = sizeof(uint64_t) * chunksize;
405         
406                 sr_session_send(sdi, &packet);
407                 count -= chunksize;
408         }
409 }
410
411 /* Parse the data section of VCD */
412 static void parse_contents(FILE *file, const struct sr_dev_inst *sdi, struct context *ctx)
413 {
414         GString *token = g_string_sized_new(32);
415         
416         uint64_t prev_timestamp = 0;
417         uint64_t prev_values = 0;
418         
419         /* Read one space-delimited token at a time. */
420         while (read_until(file, NULL, 'N') && read_until(file, token, 'W'))
421         {
422                 if (token->str[0] == '#' && g_ascii_isdigit(token->str[1]))
423                 {
424                         /* Numeric value beginning with # is a new timestamp value */
425                         uint64_t timestamp;
426                         timestamp = strtoull(token->str + 1, NULL, 10);
427                         
428                         if (ctx->downsample > 1)
429                                 timestamp /= ctx->downsample;
430                         
431                         /* Skip < 0 => skip until first timestamp.
432                          * Skip = 0 => don't skip
433                          * Skip > 0 => skip until timestamp >= skip.
434                          */
435                         if (ctx->skip < 0)
436                         {
437                                 ctx->skip = timestamp;
438                                 prev_timestamp = timestamp;
439                         }
440                         else if (ctx->skip > 0 && timestamp < (uint64_t)ctx->skip)
441                         {
442                                 prev_timestamp = ctx->skip;
443                         }
444                         else if (timestamp == prev_timestamp)
445                         {
446                                 /* Ignore repeated timestamps (e.g. sigrok outputs these) */
447                         }
448                         else
449                         {
450                                 sr_dbg("New timestamp: %" PRIu64, timestamp);
451                         
452                                 /* Generate samples from prev_timestamp up to timestamp - 1. */
453                                 send_samples(sdi, prev_values, timestamp - prev_timestamp);
454                                 prev_timestamp = timestamp;
455                         }
456                 }
457                 else if (token->str[0] == '$' && token->len > 1)
458                 {
459                         /* This is probably a $dumpvars, $comment or similar.
460                          * $dump* contain useful data, but other tags will be skipped until $end. */
461                         if (g_strcmp0(token->str, "$dumpvars") == 0 ||
462                             g_strcmp0(token->str, "$dumpon") == 0 ||
463                             g_strcmp0(token->str, "$dumpoff") == 0 ||
464                             g_strcmp0(token->str, "$end") == 0)
465                         {
466                                 /* Ignore, parse contents as normally. */
467                         }
468                         else
469                         {
470                                 /* Skip until $end */
471                                 read_until(file, NULL, '$');
472                         }
473                 }
474                 else if (strchr("bBrR", token->str[0]) != NULL)
475                 {
476                         /* A vector value. Skip it and also the following identifier. */
477                         read_until(file, NULL, 'N');
478                         read_until(file, NULL, 'W');
479                 }
480                 else if (strchr("01xXzZ", token->str[0]) != NULL)
481                 {
482                         /* A new 1-bit sample value */
483                         int i, bit;
484                         bit = (token->str[0] == '1');
485                 
486                         g_string_erase(token, 0, 1);
487                         if (token->len == 0)
488                         {
489                                 /* There was a space between value and identifier.
490                                  * Read in the rest.
491                                  */
492                                 read_until(file, NULL, 'N');
493                                 read_until(file, token, 'W');
494                         }
495                         
496                         for (i = 0; i < ctx->probecount; i++)
497                         {
498                                 if (g_strcmp0(token->str, ctx->probes[i].identifier) == 0)
499                                 {
500                                         sr_dbg("Probe %d new value %d.", i, bit);
501                                 
502                                         /* Found our probe */
503                                         if (bit)
504                                                 prev_values |= (1 << i);
505                                         else
506                                                 prev_values &= ~(1 << i);
507                                         
508                                         break;
509                                 }
510                         }
511                         
512                         if (i == ctx->probecount)
513                         {
514                                 sr_dbg("Did not find probe for identifier '%s'.", token->str);
515                         }
516                 }
517                 else
518                 {
519                         sr_warn("Skipping unknown token '%s'.", token->str);
520                 }
521                 
522                 g_string_truncate(token, 0);
523         }
524         
525         g_string_free(token, TRUE);
526 }
527
528 static int loadfile(struct sr_input *in, const char *filename)
529 {
530         struct sr_datafeed_header header;
531         struct sr_datafeed_packet packet;
532         struct sr_datafeed_meta_logic meta;
533         FILE *file;
534         struct context *ctx;
535
536         ctx = in->internal;
537
538         if ((file = fopen(filename, "r")) == NULL)
539                 return SR_ERR;
540
541         if (!parse_header(file, ctx))
542         {
543                 sr_err("VCD parsing failed");
544                 fclose(file);
545                 return SR_ERR;
546         }
547
548         /* Send header packet to the session bus. */
549         header.feed_version = 1;
550         gettimeofday(&header.starttime, NULL);
551         packet.type = SR_DF_HEADER;
552         packet.payload = &header;
553         sr_session_send(in->sdi, &packet);
554
555         /* Send metadata about the SR_DF_LOGIC packets to come. */
556         packet.type = SR_DF_META_LOGIC;
557         packet.payload = &meta;
558         meta.samplerate = ctx->samplerate / ctx->downsample;
559         meta.num_probes = ctx->probecount;
560         sr_session_send(in->sdi, &packet);
561
562         /* Parse the contents of the VCD file */
563         parse_contents(file, in->sdi, ctx);
564         
565         /* Send end packet to the session bus. */
566         packet.type = SR_DF_END;
567         sr_session_send(in->sdi, &packet);
568
569         fclose(file);
570         release_context(ctx);
571         in->internal = NULL;
572
573         return SR_OK;
574 }
575
576 SR_PRIV struct sr_input_format input_vcd = {
577         .id = "vcd",
578         .description = "Value Change Dump",
579         .format_match = format_match,
580         .init = init,
581         .loadfile = loadfile,
582 };