2 * This file is part of the sigrok project.
4 * Copyright (C) 2012 Petteri Aimonen <jpa@sr.mail.kapsi.fi>
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.
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.
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/>.
20 /* The VCD input module has the following options:
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.
26 * skip: Allows skipping until given timestamp in the file.
27 * This can speed up analyzing of long captures.
29 * Value < 0: Skip until first timestamp listed in
32 * Value = 0: Do not skip, instead generate samples
33 * beginning from timestamp 0.
35 * Value > 0: Start at the given timestamp.
37 * downsample: Divide the samplerate by the given factor.
38 * This can speed up analyzing of long captures.
40 * Based on Verilog standard IEEE Std 1364-2001 Version C
43 * - $var with 'wire' and 'reg' types of scalar variables
44 * - $timescale definition for samplerate
45 * - multiple character variable identifiers
47 * Most important unsupported features:
48 * - vector variables (bit vectors etc.)
49 * - analog, integer and real number variables
50 * - $dumpvars initial value declaration
59 #include "libsigrok.h"
60 #include "libsigrok-internal.h"
62 /* Message logging helpers with driver-specific prefix string. */
63 #define DRIVER_LOG_DOMAIN "input/vcd: "
64 #define sr_log(l, s, args...) sr_log(l, DRIVER_LOG_DOMAIN s, ## args)
65 #define sr_spew(s, args...) sr_spew(DRIVER_LOG_DOMAIN s, ## args)
66 #define sr_dbg(s, args...) sr_dbg(DRIVER_LOG_DOMAIN s, ## args)
67 #define sr_info(s, args...) sr_info(DRIVER_LOG_DOMAIN s, ## args)
68 #define sr_warn(s, args...) sr_warn(DRIVER_LOG_DOMAIN s, ## args)
69 #define sr_err(s, args...) sr_err(DRIVER_LOG_DOMAIN s, ## args)
71 #define DEFAULT_NUM_PROBES 8
73 /* Read until specific type of character occurs in file.
74 * Skip input if dest is NULL.
76 * 'W' read until whitespace
77 * 'N' read until non-whitespace, and ungetc() the character
80 static gboolean read_until(FILE *file, GString *dest, char mode)
90 sr_err("Unexpected EOF.");
94 if (mode == 'W' && g_ascii_isspace(c))
97 if (mode == 'N' && !g_ascii_isspace(c))
105 prev[0] = prev[1]; prev[1] = prev[2]; prev[2] = prev[3]; prev[3] = c;
106 if (prev[0] == '$' && prev[1] == 'e' && prev[2] == 'n' && prev[3] == 'd')
109 g_string_truncate(dest, dest->len - 3);
116 g_string_append_c(dest, c);
120 /* Reads a single VCD section from input file and parses it to structure.
121 * e.g. $timescale 1ps $end => "timescale" "1ps"
123 static gboolean parse_section(FILE *file, gchar **name, gchar **contents)
126 GString *sname, *scontents;
128 /* Skip any initial white-space */
129 if (!read_until(file, NULL, 'N')) return FALSE;
131 /* Section tag should start with $. */
132 if (fgetc(file) != '$')
134 sr_err("Expected $ at beginning of section.");
138 /* Read the section tag */
139 sname = g_string_sized_new(32);
140 status = read_until(file, sname, 'W');
142 /* Skip whitespace before content */
143 status = status && read_until(file, NULL, 'N');
145 /* Read the content */
146 scontents = g_string_sized_new(128);
147 status = status && read_until(file, scontents, '$');
148 g_strchomp(scontents->str);
150 /* Release strings if status is FALSE, return them if status is TRUE */
151 *name = g_string_free(sname, !status);
152 *contents = g_string_free(scontents, !status);
169 struct probe probes[SR_MAX_NUM_PROBES];
172 static void release_context(struct context *ctx)
175 for (i = 0; i < ctx->probecount; i++)
177 g_free(ctx->probes[i].name); ctx->probes[i].name = NULL;
178 g_free(ctx->probes[i].identifier); ctx->probes[i].identifier = NULL;
184 /* Remove empty parts from an array returned by g_strsplit. */
185 static void remove_empty_parts(gchar **parts)
188 gchar **dest = parts;
202 /* Parse VCD header to get values for context structure.
203 * The context structure should be zeroed before calling this.
205 static gboolean parse_header(FILE *file, struct context *ctx)
207 gchar *name = NULL, *contents = NULL;
208 gboolean status = FALSE;
210 while (parse_section(file, &name, &contents))
212 sr_dbg("Section '%s', contents '%s'.", name, contents);
214 if (g_strcmp0(name, "enddefinitions") == 0)
219 else if (g_strcmp0(name, "timescale") == 0)
221 /* The standard allows for values 1, 10 or 100
222 * and units s, ms, us, ns, ps and fs. */
223 struct sr_rational period;
224 if (sr_parse_period(contents, &period) == SR_OK)
226 ctx->samplerate = period.q / period.p;
227 if (period.q % period.p != 0)
229 /* Does not happen unless time value is non-standard */
230 sr_warn("Inexact rounding of samplerate, %" PRIu64 " / %" PRIu64 " to %" PRIu64 " Hz.",
231 period.q, period.p, ctx->samplerate);
234 sr_dbg("Samplerate: %" PRIu64, ctx->samplerate);
238 sr_err("Parsing timescale failed.");
241 else if (g_strcmp0(name, "var") == 0)
243 /* Format: $var type size identifier reference $end */
244 gchar **parts = g_strsplit_set(contents, " \r\n\t", 0);
245 remove_empty_parts(parts);
247 if (g_strv_length(parts) != 4)
249 sr_err("$var section should have 4 items");
251 else if (g_strcmp0(parts[0], "reg") != 0 && g_strcmp0(parts[0], "wire") != 0)
253 sr_warn("Unsupported signal type: '%s'", parts[0]);
255 else if (strtol(parts[1], NULL, 10) != 1)
257 sr_warn("Unsupported signal size: '%s'", parts[1]);
259 else if (ctx->probecount >= ctx->maxprobes)
261 sr_warn("Skipping '%s' because only %d probes requested.", parts[3], ctx->maxprobes);
265 sr_info("Probe %d is '%s' identified by '%s'.", ctx->probecount, parts[3], parts[2]);
266 ctx->probes[ctx->probecount].identifier = g_strdup(parts[2]);
267 ctx->probes[ctx->probecount].name = g_strdup(parts[3]);
274 g_free(name); name = NULL;
275 g_free(contents); contents = NULL;
284 static int format_match(const char *filename)
287 gchar *name = NULL, *contents = NULL;
290 file = fopen(filename, "r");
294 /* If we can parse the first section correctly,
295 * then it is assumed to be a VCD file.
297 status = parse_section(file, &name, &contents);
298 status = status && (*name != '\0');
307 static int init(struct sr_input *in)
309 struct sr_probe *probe;
311 char name[SR_MAX_PROBENAME_LEN + 1];
315 if (!(ctx = g_try_malloc0(sizeof(*ctx)))) {
316 sr_err("Input format context malloc failed.");
317 return SR_ERR_MALLOC;
320 num_probes = DEFAULT_NUM_PROBES;
326 param = g_hash_table_lookup(in->param, "numprobes");
328 num_probes = strtoul(param, NULL, 10);
331 release_context(ctx);
336 param = g_hash_table_lookup(in->param, "downsample");
338 ctx->downsample = strtoul(param, NULL, 10);
339 if (ctx->downsample < 1)
345 param = g_hash_table_lookup(in->param, "skip");
347 ctx->skip = strtoul(param, NULL, 10) / ctx->downsample;
351 /* Maximum number of probes to parse from the VCD */
352 ctx->maxprobes = num_probes;
354 /* Create a virtual device. */
355 in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
358 for (i = 0; i < num_probes; i++) {
359 snprintf(name, SR_MAX_PROBENAME_LEN, "%d", i);
361 if (!(probe = sr_probe_new(i, SR_PROBE_LOGIC, TRUE, name)))
363 release_context(ctx);
367 in->sdi->probes = g_slist_append(in->sdi->probes, probe);
373 #define CHUNKSIZE 1024
375 /* Send N samples of the given value. */
376 static void send_samples(const struct sr_dev_inst *sdi, uint64_t sample, uint64_t count)
378 struct sr_datafeed_packet packet;
379 struct sr_datafeed_logic logic;
380 uint64_t buffer[CHUNKSIZE];
382 unsigned chunksize = CHUNKSIZE;
384 if (count < chunksize)
387 for (i = 0; i < chunksize; i++)
392 packet.type = SR_DF_LOGIC;
393 packet.payload = &logic;
394 logic.unitsize = sizeof(uint64_t);
399 if (count < chunksize)
402 logic.length = sizeof(uint64_t) * chunksize;
404 sr_session_send(sdi, &packet);
409 /* Parse the data section of VCD */
410 static void parse_contents(FILE *file, const struct sr_dev_inst *sdi, struct context *ctx)
412 GString *token = g_string_sized_new(32);
414 uint64_t prev_timestamp = 0;
415 uint64_t new_values = 0;
416 uint64_t prev_values = 0;
418 /* Read one space-delimited token at a time. */
419 while (read_until(file, NULL, 'N') && read_until(file, token, 'W'))
421 if (token->str[0] == '#' && g_ascii_isdigit(token->str[1]))
423 /* Numeric value beginning with # is a new timestamp value */
425 timestamp = strtoull(token->str + 1, NULL, 10);
427 if (ctx->downsample > 1)
428 timestamp /= ctx->downsample;
430 /* Skip < 0 => skip until first timestamp.
431 * Skip = 0 => don't skip
432 * Skip > 0 => skip until timestamp >= skip.
436 ctx->skip = timestamp;
438 else if (ctx->skip > 0 && timestamp < (uint64_t)ctx->skip)
440 prev_timestamp = ctx->skip - 1;
442 else if (timestamp == prev_timestamp)
444 /* This only occurs when ctx->downsample > 1 */
445 if (prev_values != new_values)
447 sr_warn("VCD downsampling hides a glitch at %" PRIu64, timestamp);
448 prev_values = new_values;
453 sr_dbg("New timestamp: %" PRIu64, timestamp);
455 /* Generate samples from prev_timestamp up to timestamp - 1. */
456 send_samples(sdi, new_values, timestamp - prev_timestamp);
458 prev_timestamp = timestamp;
459 prev_values = new_values;
462 else if (token->str[0] == '$')
464 /* This is probably a $dumpvars, $comment or similar.
465 * For now, just skip it until $end. */
466 read_until(file, NULL, '$');
468 else if (strchr("01xXzZ", token->str[0]) != NULL)
470 /* A new 1-bit sample value */
472 bit = (token->str[0] == '1');
474 g_string_erase(token, 0, 1);
477 /* There was a space between value and identifier.
480 read_until(file, NULL, 'N');
481 read_until(file, token, 'W');
484 for (i = 0; i < ctx->probecount; i++)
486 if (g_strcmp0(token->str, ctx->probes[i].identifier) == 0)
488 sr_dbg("Probe %d new value %d.", i, bit);
490 /* Found our probe */
492 new_values |= (1 << i);
494 new_values &= ~(1 << i);
500 if (i == ctx->probecount)
502 sr_info("Did not find probe for identifier '%s'.", token->str);
506 g_string_truncate(token, 0);
509 g_string_free(token, TRUE);
512 static int loadfile(struct sr_input *in, const char *filename)
514 struct sr_datafeed_header header;
515 struct sr_datafeed_packet packet;
516 struct sr_datafeed_meta_logic meta;
522 if ((file = fopen(filename, "r")) == NULL)
525 if (!parse_header(file, ctx))
527 sr_err("VCD parsing failed");
532 /* Send header packet to the session bus. */
533 header.feed_version = 1;
534 gettimeofday(&header.starttime, NULL);
535 packet.type = SR_DF_HEADER;
536 packet.payload = &header;
537 sr_session_send(in->sdi, &packet);
539 /* Send metadata about the SR_DF_LOGIC packets to come. */
540 packet.type = SR_DF_META_LOGIC;
541 packet.payload = &meta;
542 meta.samplerate = ctx->samplerate / ctx->downsample;
543 meta.num_probes = ctx->probecount;
544 sr_session_send(in->sdi, &packet);
546 /* Parse the contents of the VCD file */
547 parse_contents(file, in->sdi, ctx);
549 /* Send end packet to the session bus. */
550 packet.type = SR_DF_END;
551 sr_session_send(in->sdi, &packet);
554 release_context(ctx);
560 SR_PRIV struct sr_input_format input_vcd = {
562 .description = "Value Change Dump",
563 .format_match = format_match,
565 .loadfile = loadfile,