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