Skip to content

Commit 3d5c97b

Browse files
ccojocarCosmin Cojocar
authored andcommitted
Add a test sample for Cgo files
Signed-off-by: Cosmin Cojocar <[email protected]>
1 parent 81e8278 commit 3d5c97b

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

analyzer_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,21 @@ var _ = Describe("Analyzer", func() {
339339
Expect(issues).Should(HaveLen(1))
340340
})
341341
})
342+
It("should be able to analyze Cgo files", func() {
343+
analyzer.LoadRules(rules.Generate().Builders())
344+
sample := testutils.SampleCodeCgo[0]
345+
source := sample.Code[0]
346+
347+
testPackage := testutils.NewTestPackage()
348+
defer testPackage.Close()
349+
testPackage.AddFile("main.go", source)
350+
err := testPackage.Build()
351+
Expect(err).ShouldNot(HaveOccurred())
352+
err = analyzer.Process(buildTags, testPackage.Path)
353+
Expect(err).ShouldNot(HaveOccurred())
354+
issues, _, _ := analyzer.Report()
355+
Expect(issues).Should(HaveLen(0))
356+
})
342357

343358
Context("when parsing errors from a package", func() {
344359

testutils/source.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1541,4 +1541,49 @@ package main
15411541
func main() {
15421542
fmt.Println("no package imported error")
15431543
}`}, 1, gosec.NewConfig()}}
1544+
1545+
// SampleCodeCgo - Cgo file sample
1546+
SampleCodeCgo = []CodeSample{{[]string{`
1547+
package main
1548+
1549+
import (
1550+
"fmt"
1551+
"unsafe"
1552+
)
1553+
1554+
/*
1555+
#include <stdlib.h>
1556+
#include <stdio.h>
1557+
#include <string.h>
1558+
1559+
int printData(unsigned char *data) {
1560+
return printf("cData: %lu \"%s\"\n", (long unsigned int)strlen(data), data);
1561+
}
1562+
*/
1563+
import "C"
1564+
1565+
func main() {
1566+
// Allocate C data buffer.
1567+
width, height := 8, 2
1568+
lenData := width * height
1569+
// add string terminating null byte
1570+
cData := (*C.uchar)(C.calloc(C.size_t(lenData+1), C.sizeof_uchar))
1571+
1572+
// When no longer in use, free C allocations.
1573+
defer C.free(unsafe.Pointer(cData))
1574+
1575+
// Go slice reference to C data buffer,
1576+
// minus string terminating null byte
1577+
gData := (*[1 << 30]byte)(unsafe.Pointer(cData))[:lenData:lenData]
1578+
1579+
// Write and read cData via gData.
1580+
for i := range gData {
1581+
gData[i] = '.'
1582+
}
1583+
copy(gData[0:], "Data")
1584+
gData[len(gData)-1] = 'X'
1585+
fmt.Printf("gData: %d %q\n", len(gData), gData)
1586+
C.printData(cData)
1587+
}
1588+
`}, 0, gosec.NewConfig()}}
15441589
)

0 commit comments

Comments
 (0)