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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// Copyright (C) 2015  Daniel Trebbien
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library.  If not, see <http://www.gnu.org/licenses/>.

use std::fmt::{Display, Error, Formatter};
use std::io::{BufRead};
use std::iter::{IntoIterator};
use std::option::{Option};
use std::result::{Result};
use std::slice::{Iter, IterMut};
use std::str::{FromStr};
use std::string::{String};
use std::vec::{Vec};

/// Holds information about a parse error generated while parsing a suppressions file.
pub struct ParseError {
    /// Line number where the parse error occurred.
    pub lineno: usize,

    /// Description of the parse error.
    pub message: String,
}

impl Display for ParseError {
    fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
        write!(fmt, "line {}: {}", self.lineno, self.message)
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum Frame {
    /// A frame-level wildcard, represented by `'...'`.
    FrameWildcard,

    /// An object frame.
    ObjFrame {
        /// A file glob for the path to the object file. This may contain wildcard characters
        /// `*` and `?`.
        glob: String,
    },

    /// A function frame.
    FunFrame {
        /// Glob for the name of the function. This may contain wildcard characters `*` and `?`.
        glob: String,
    },
}

impl Display for Frame {
    fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
        use Frame::*;
        match *self {
            FrameWildcard => write!(fmt, "..."),
            ObjFrame { ref glob } => {
                write!(fmt, "obj:{}", glob)
            },
            FunFrame { ref glob } => {
                write!(fmt, "fun:{}", glob)
            },
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum SuppressionType {
    MemcheckAddr(usize),
    MemcheckCond,
    MemcheckFree,
    MemcheckLeak,
    MemcheckOverlap,
    MemcheckParam,
    MemcheckValue(usize),
    OtherType {
        tool_name: String,
        suppression_type: String,
    },
}

impl Display for SuppressionType {
    fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
        use SuppressionType::*;
        match *self {
            MemcheckAddr(n) => write!(fmt, "Memcheck:Addr{}", n),
            MemcheckCond => write!(fmt, "Memcheck:Cond"),
            MemcheckFree => write!(fmt, "Memcheck:Free"),
            MemcheckLeak => write!(fmt, "Memcheck:Leak"),
            MemcheckOverlap => write!(fmt, "Memcheck:Overlap"),
            MemcheckParam => write!(fmt, "Memcheck:Param"),
            MemcheckValue(n) => write!(fmt, "Memcheck:Value{}", n),
            OtherType { ref tool_name, ref suppression_type } => {
                write!(fmt, "{}:{}", tool_name, suppression_type)
            },
        }
    }
}

/// Holds information about a single Valgrind suppression.
#[derive(Clone, Debug, PartialEq)]
pub struct Suppression {
    /// The name of the suppression.
    pub name: String,
    /// The type of suppression.
    pub type_: SuppressionType,
    /// Any extra information, where used by the suppression type (e.g. a Memcheck `Param` suppression).
    pub opt_extra_info: Option<Vec<String>>,
    /// The calling context of the suppression.
    pub frames: Vec<Frame>,
}

impl Display for Suppression {
    fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
        try!(writeln!(fmt, "{{"));
        try!(writeln!(fmt, "   {}", self.name));
        try!(writeln!(fmt, "   {}", self.type_));
        if let Some(ref extra_info) = self.opt_extra_info {
            for line in extra_info {
                try!(writeln!(fmt, "   {}", line));
            }
        }
        for frame in &self.frames {
            try!(writeln!(fmt, "   {}", frame));
        }
        write!(fmt, "}}")
    }
}

/// A set of Valgrind suppressions.
#[derive(Clone)]
pub struct Suppressions {
    suppressions: Vec<Suppression>
}

enum ParseState {
    BeforeOpeningBrace,
    AfterOpeningBrace {
        opening_brace_lineno: usize,
    },
    HaveName {
        opening_brace_lineno: usize,
        name: String,
    },
    HaveSuppressionType {
        opening_brace_lineno: usize,
        name: String,
        tool_names: Vec<String>,
        suppression_type: String,
        /// Lines of extra information, used by some suppression types (e.g. a Memcheck `Param` suppression).
        opt_extra_info: Option<Vec<String>>,
    },
    HaveOptExtraInfo {
        opening_brace_lineno: usize,
        name: String,
        tool_names: Vec<String>,
        suppression_type: String,
        opt_extra_info: Option<Vec<String>>,
        frames: Vec<Frame>,
    },
}

impl Suppressions {

    /// Parses the suppressions from `buf` in Valgrind suppression syntax.
    ///
    /// # See also
    /// * [Suppressing errors](http://valgrind.org/docs/manual/manual-core.html#manual-core.suppress). Valgrind User Manual.
    pub fn parse<B: BufRead>(buf: &mut B) -> Result<Suppressions, ParseError> {
        use ParseState::*;

        let mut suppressions: Vec<Suppression> = Vec::new();
        let mut lineno = 0;
        let mut state = BeforeOpeningBrace;
        for line_res in buf.lines() {
            match line_res {
                Err(e) => {
                    return Err(ParseError {
                        lineno: lineno,
                        message: format!("IoError returned: {}", e),
                    });
                },
                Ok(line) => {
                    lineno = lineno + 1;

                    let trimmed_line = line.trim();
                    if !trimmed_line.is_empty() && !trimmed_line.starts_with("#") {
                        state = match state {
                                BeforeOpeningBrace => {
                                    if trimmed_line == "{" {
                                        AfterOpeningBrace {
                                            opening_brace_lineno: lineno
                                        }
                                    } else if trimmed_line.starts_with('{') {
                                        return Err(ParseError {
                                            lineno: lineno,
                                            message: "expecting an opening brace on its own line".to_string(),
                                        });
                                    } else {
                                        return Err(ParseError {
                                            lineno: lineno,
                                            message: "expecting an opening brace".to_string(),
                                        });
                                    }
                                },
                                AfterOpeningBrace { opening_brace_lineno } => {
                                    // If there is a closing brace immediately after the opening brace,
                                    // then skip this "empty" suppression (go back to the BeforeOpeningBrace
                                    // state).
                                    if trimmed_line == "}" {
                                        BeforeOpeningBrace
                                    } else if trimmed_line.contains('}') {
                                        return Err(ParseError {
                                            lineno: lineno,
                                            message: "the suppression name cannot contain a closing brace '}'".to_string(),
                                        });
                                    } else {
                                        HaveName {
                                            opening_brace_lineno: opening_brace_lineno,
                                            name: trimmed_line.to_string(),
                                        }
                                    }
                                },
                                HaveName { opening_brace_lineno, name } => {
                                    let colon_pos = match trimmed_line.find(':') {
                                            None => {
                                                return Err(ParseError {
                                                    lineno: lineno,
                                                    message: "no suppression type was found".to_string(),
                                                });
                                            }
                                            Some(colon_pos) => colon_pos,
                                        };
                                    let splits = trimmed_line[..colon_pos].split(',');
                                    let tool_names: Vec<String> = splits.map(|part| part.to_string()).collect();
                                    HaveSuppressionType {
                                        opening_brace_lineno: opening_brace_lineno,
                                        name: name,
                                        tool_names: tool_names,
                                        suppression_type: trimmed_line[colon_pos + 1..].to_string(),
                                        opt_extra_info: None,
                                    }
                                },
                                HaveSuppressionType {
                                    opening_brace_lineno,
                                    name,
                                    tool_names,
                                    suppression_type,
                                    mut opt_extra_info,
                                } => {
                                    if trimmed_line == "..." {
                                        HaveOptExtraInfo {
                                            opening_brace_lineno: opening_brace_lineno,
                                            name: name,
                                            tool_names: tool_names,
                                            suppression_type: suppression_type,
                                            opt_extra_info: opt_extra_info,
                                            frames: vec![Frame::FrameWildcard],
                                        }
                                    } else if trimmed_line.starts_with("obj:") {
                                        let glob = trimmed_line[4..].trim_left().to_string();
                                        HaveOptExtraInfo {
                                            opening_brace_lineno: opening_brace_lineno,
                                            name: name,
                                            tool_names: tool_names,
                                            suppression_type: suppression_type,
                                            opt_extra_info: opt_extra_info,
                                            frames: vec![Frame::ObjFrame { glob: glob }],
                                        }
                                    } else if trimmed_line.starts_with("fun:") {
                                        let glob = trimmed_line[4..].trim_left().to_string();
                                        HaveOptExtraInfo {
                                            opening_brace_lineno: opening_brace_lineno,
                                            name: name,
                                            tool_names: tool_names,
                                            suppression_type: suppression_type,
                                            opt_extra_info: opt_extra_info,
                                            frames: vec![Frame::FunFrame { glob: glob }],
                                        }
                                    // If there is no calling context for this suppression, then skip it.
                                    // TODO This might not be 100% correct. Perhaps some suppressions only use extra info?
                                    } else if trimmed_line == "}" {
                                        BeforeOpeningBrace
                                    } else {
                                        if let Some(ref mut extra_info) = opt_extra_info {
                                            extra_info.push(trimmed_line.to_string());
                                        } else {
                                            opt_extra_info = Some(vec![trimmed_line.to_string()]);
                                        }
                                        HaveSuppressionType {
                                            opening_brace_lineno: opening_brace_lineno,
                                            name: name,
                                            tool_names: tool_names,
                                            suppression_type: suppression_type,
                                            opt_extra_info: opt_extra_info,
                                        }
                                    }
                                },
                                HaveOptExtraInfo {
                                    opening_brace_lineno,
                                    name,
                                    tool_names,
                                    suppression_type,
                                    opt_extra_info,
                                    mut frames,
                                } => {
                                    if trimmed_line == "..." {
                                        frames.push(Frame::FrameWildcard);
                                        HaveOptExtraInfo {
                                            opening_brace_lineno: opening_brace_lineno,
                                            name: name,
                                            tool_names: tool_names,
                                            suppression_type: suppression_type,
                                            opt_extra_info: opt_extra_info,
                                            frames: frames,
                                        }
                                    } else if trimmed_line.starts_with("obj:") {
                                        frames.push(Frame::ObjFrame {
                                            glob: trimmed_line[4..].trim_left().to_string(),
                                        });
                                        HaveOptExtraInfo {
                                            opening_brace_lineno: opening_brace_lineno,
                                            name: name,
                                            tool_names: tool_names,
                                            suppression_type: suppression_type,
                                            opt_extra_info: opt_extra_info,
                                            frames: frames,
                                        }
                                    } else if trimmed_line.starts_with("fun:") {
                                        frames.push(Frame::FunFrame {
                                            glob: trimmed_line[4..].trim_left().to_string(),
                                        });
                                        HaveOptExtraInfo {
                                            opening_brace_lineno: opening_brace_lineno,
                                            name: name,
                                            tool_names: tool_names,
                                            suppression_type: suppression_type,
                                            opt_extra_info: opt_extra_info,
                                            frames: frames,
                                        }
                                    } else if trimmed_line == "}" {
                                        suppressions.extend(tool_names.iter().map(|tool_name| -> Suppression {
                                            let type_ = if tool_name == "Memcheck" {
                                                    if suppression_type.starts_with("Addr") {
                                                        match usize::from_str(&suppression_type[4..]) {
                                                            Err(_) => SuppressionType::OtherType {
                                                                tool_name: tool_name.to_string(),
                                                                suppression_type: suppression_type.clone(),
                                                            },
                                                            Ok(n) => SuppressionType::MemcheckAddr(n),
                                                        }
                                                    } else if suppression_type == "Cond" {
                                                        SuppressionType::MemcheckCond
                                                    } else if suppression_type == "Free" {
                                                        SuppressionType::MemcheckFree
                                                    } else if suppression_type == "Leak" {
                                                        SuppressionType::MemcheckLeak
                                                    } else if suppression_type == "Overlap" {
                                                        SuppressionType::MemcheckOverlap
                                                    } else if suppression_type == "Param" {
                                                        SuppressionType::MemcheckParam
                                                    } else if suppression_type.starts_with("Value") {
                                                        match usize::from_str(&suppression_type[5..]) {
                                                            Err(_) => SuppressionType::OtherType {
                                                                tool_name: tool_name.to_string(),
                                                                suppression_type: suppression_type.clone(),
                                                            },
                                                            Ok(n) => SuppressionType::MemcheckValue(n),
                                                        }
                                                    } else {
                                                        SuppressionType::OtherType {
                                                            tool_name: tool_name.to_string(),
                                                            suppression_type: suppression_type.clone(),
                                                        }
                                                    }
                                                } else {
                                                    SuppressionType::OtherType {
                                                        tool_name: tool_name.to_string(),
                                                        suppression_type: suppression_type.clone(),
                                                    }
                                                };
                                            Suppression {
                                                name: name.clone(),
                                                type_: type_,
                                                opt_extra_info: opt_extra_info.clone(),
                                                frames: frames.clone(),
                                            }
                                        }));

                                        BeforeOpeningBrace
                                    } else {
                                        return Err(ParseError {
                                            lineno: lineno,
                                            message: "invalid calling context line".to_string(),
                                        });
                                    }
                                },
                            }; // end match state
                    }
                }, // end Ok(line)
            }
        }
        match state {
            AfterOpeningBrace {
                opening_brace_lineno,
                ..
            } => {
                return Err(ParseError {
                    lineno: opening_brace_lineno,
                    message: "unexpectedly encountered EOF while parsing a suppression".to_string(),
                });
            },
            HaveName {
                opening_brace_lineno,
                name,
            } => {
                return Err(ParseError {
                    lineno: opening_brace_lineno,
                    message: format!("unexpectedly encountered EOF while parsing the suppression named '{}'", name),
                });
            },
            HaveSuppressionType {
                opening_brace_lineno,
                name,
                ..
            } => {
                return Err(ParseError {
                    lineno: opening_brace_lineno,
                    message: format!("unexpectedly encountered EOF while parsing the suppression named '{}'", name),
                });
            },
            HaveOptExtraInfo {
                opening_brace_lineno,
                name,
                ..
            } => {
                return Err(ParseError {
                    lineno: opening_brace_lineno,
                    message: format!("unexpectedly encountered EOF while parsing the suppression named '{}'", name),
                });
            },
            _ => (),
        }

        Ok(Suppressions {
            suppressions: suppressions,
        })
    }

    /// Clones all of the suppressions in `other` and adds them to these suppressions.
    pub fn add_all(&mut self, other: &Suppressions) {
        self.suppressions.extend(other.suppressions.iter().cloned());
    }

    pub fn count(&self) -> usize {
        self.suppressions.len()
    }

    pub fn iter(&self) -> Iter<Suppression> {
        self.suppressions.iter()
    }

    pub fn iter_mut(&mut self) -> IterMut<Suppression> {
        self.suppressions.iter_mut()
    }
}

impl Display for Suppressions {
    fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
        for suppression in &self.suppressions {
            try!(writeln!(fmt, "{}", suppression));
        }
        Ok(())
    }
}

impl<'a> IntoIterator for &'a Suppressions {
    type Item = &'a Suppression;
    type IntoIter = Iter<'a, Suppression>;

    fn into_iter(self) -> Iter<'a, Suppression> {
        self.iter()
    }
}