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