0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /// Use kstrdup rather than duplicating its implementation
0003 ///
0004 // Confidence: High
0005 // Copyright: (C) 2010-2012 Nicolas Palix.
0006 // Copyright: (C) 2010-2012 Julia Lawall, INRIA/LIP6.
0007 // Copyright: (C) 2010-2012 Gilles Muller, INRIA/LiP6.
0008 // URL: https://coccinelle.gitlabpages.inria.fr/website
0009 // Comments:
0010 // Options: --no-includes --include-headers
0011
0012 virtual patch
0013 virtual context
0014 virtual org
0015 virtual report
0016
0017 @depends on patch@
0018 expression from,to;
0019 expression flag,E1,E2;
0020 statement S;
0021 @@
0022
0023 - to = kmalloc(strlen(from) + 1,flag);
0024 + to = kstrdup(from, flag);
0025 ... when != \(from = E1 \| to = E1 \)
0026 if (to==NULL || ...) S
0027 ... when != \(from = E2 \| to = E2 \)
0028 - strcpy(to, from);
0029
0030 @depends on patch@
0031 expression x,from,to;
0032 expression flag,E1,E2,E3;
0033 statement S;
0034 @@
0035
0036 - x = strlen(from) + 1;
0037 ... when != \( x = E1 \| from = E1 \)
0038 - to = \(kmalloc\|kzalloc\)(x,flag);
0039 + to = kstrdup(from, flag);
0040 ... when != \(x = E2 \| from = E2 \| to = E2 \)
0041 if (to==NULL || ...) S
0042 ... when != \(x = E3 \| from = E3 \| to = E3 \)
0043 - memcpy(to, from, x);
0044
0045 // ---------------------------------------------------------------------
0046
0047 @r1 depends on !patch exists@
0048 expression from,to;
0049 expression flag,E1,E2;
0050 statement S;
0051 position p1,p2;
0052 @@
0053
0054 * to = kmalloc@p1(strlen(from) + 1,flag);
0055 ... when != \(from = E1 \| to = E1 \)
0056 if (to==NULL || ...) S
0057 ... when != \(from = E2 \| to = E2 \)
0058 * strcpy@p2(to, from);
0059
0060 @r2 depends on !patch exists@
0061 expression x,from,to;
0062 expression flag,E1,E2,E3;
0063 statement S;
0064 position p1,p2;
0065 @@
0066
0067 * x = strlen(from) + 1;
0068 ... when != \( x = E1 \| from = E1 \)
0069 * to = \(kmalloc@p1\|kzalloc@p1\)(x,flag);
0070 ... when != \(x = E2 \| from = E2 \| to = E2 \)
0071 if (to==NULL || ...) S
0072 ... when != \(x = E3 \| from = E3 \| to = E3 \)
0073 * memcpy@p2(to, from, x);
0074
0075 @script:python depends on org@
0076 p1 << r1.p1;
0077 p2 << r1.p2;
0078 @@
0079
0080 cocci.print_main("WARNING opportunity for kstrdup",p1)
0081 cocci.print_secs("strcpy",p2)
0082
0083 @script:python depends on org@
0084 p1 << r2.p1;
0085 p2 << r2.p2;
0086 @@
0087
0088 cocci.print_main("WARNING opportunity for kstrdup",p1)
0089 cocci.print_secs("memcpy",p2)
0090
0091 @script:python depends on report@
0092 p1 << r1.p1;
0093 p2 << r1.p2;
0094 @@
0095
0096 msg = "WARNING opportunity for kstrdup (strcpy on line %s)" % (p2[0].line)
0097 coccilib.report.print_report(p1[0], msg)
0098
0099 @script:python depends on report@
0100 p1 << r2.p1;
0101 p2 << r2.p2;
0102 @@
0103
0104 msg = "WARNING opportunity for kstrdup (memcpy on line %s)" % (p2[0].line)
0105 coccilib.report.print_report(p1[0], msg)