Compare commits
25 Commits
nanopb-0.2
...
maintenanc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb66254b79 | ||
|
|
641c743b27 | ||
|
|
4ce729df7f | ||
|
|
83157e3362 | ||
|
|
45fc9f3ef6 | ||
|
|
115de6e555 | ||
|
|
9c92410e2a | ||
|
|
6df566859d | ||
|
|
cc1c3a7963 | ||
|
|
33585924de | ||
|
|
b7add1e577 | ||
|
|
2f05a35b5f | ||
|
|
4f76e64929 | ||
|
|
ec3bff4ba1 | ||
|
|
1d7f60fec3 | ||
|
|
5749606f5d | ||
|
|
eaa3c7b157 | ||
|
|
3cf9668c75 | ||
|
|
7f97ad549e | ||
|
|
f2f9f8a9ed | ||
|
|
788d2825b0 | ||
|
|
99bc1d4f97 | ||
|
|
8a857a7f75 | ||
|
|
8611958a7f | ||
|
|
2e9797af58 |
@@ -1,3 +1,25 @@
|
|||||||
|
nanopb-0.2.9.2 (2015-01-24)
|
||||||
|
Fix memory leaks with PB_ENABLE_MALLOC with some submessage hierarchies (issue 138)
|
||||||
|
Fix compilation error with generated initializers for repeated pointer fields
|
||||||
|
|
||||||
|
nanopb-0.2.9.1 (2014-09-11)
|
||||||
|
Fix security issue due to size_t overflows. (issue 132)
|
||||||
|
Fix memory leak with duplicated fields and PB_ENABLE_MALLOC
|
||||||
|
Fix crash if pb_release() is called twice.
|
||||||
|
|
||||||
|
nanopb-0.2.9 (2014-08-09)
|
||||||
|
NOTE: If you are using the -e option with the generator, you have
|
||||||
|
to prepend . to the argument to get the same behaviour as before.
|
||||||
|
|
||||||
|
Do not automatically add a dot with generator -e option. (issue 122)
|
||||||
|
Fix problem with .options file and extension fields. (issue 125)
|
||||||
|
Don't use SIZE_MAX macro, as it is not in C89. (issue 120)
|
||||||
|
Generate #defines for initializing message structures. (issue 79)
|
||||||
|
Add skip_message option to generator. (issue 121)
|
||||||
|
Add PB_PACKED_STRUCT support for Keil MDK-ARM toolchain (issue 119)
|
||||||
|
Give better messages about the .options file path. (issue 124)
|
||||||
|
Improved tests
|
||||||
|
|
||||||
nanopb-0.2.8 (2014-05-20)
|
nanopb-0.2.8 (2014-05-20)
|
||||||
Fix security issue with PB_ENABLE_MALLOC. (issue 117)
|
Fix security issue with PB_ENABLE_MALLOC. (issue 117)
|
||||||
Add option to not add timestamps to .pb.h and .pb.c preambles. (issue 115)
|
Add option to not add timestamps to .pb.h and .pb.c preambles. (issue 115)
|
||||||
|
|||||||
@@ -23,9 +23,13 @@
|
|||||||
#include "fileproto.pb.h"
|
#include "fileproto.pb.h"
|
||||||
#include "common.h"
|
#include "common.h"
|
||||||
|
|
||||||
|
/* This callback function will be called once for each filename received
|
||||||
|
* from the server. The filenames will be printed out immediately, so that
|
||||||
|
* no memory has to be allocated for them.
|
||||||
|
*/
|
||||||
bool printfile_callback(pb_istream_t *stream, const pb_field_t *field, void **arg)
|
bool printfile_callback(pb_istream_t *stream, const pb_field_t *field, void **arg)
|
||||||
{
|
{
|
||||||
FileInfo fileinfo;
|
FileInfo fileinfo = {};
|
||||||
|
|
||||||
if (!pb_decode(stream, FileInfo_fields, &fileinfo))
|
if (!pb_decode(stream, FileInfo_fields, &fileinfo))
|
||||||
return false;
|
return false;
|
||||||
@@ -35,51 +39,70 @@ bool printfile_callback(pb_istream_t *stream, const pb_field_t *field, void **ar
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* This function sends a request to socket 'fd' to list the files in
|
||||||
|
* directory given in 'path'. The results received from server will
|
||||||
|
* be printed to stdout.
|
||||||
|
*/
|
||||||
bool listdir(int fd, char *path)
|
bool listdir(int fd, char *path)
|
||||||
{
|
{
|
||||||
ListFilesRequest request;
|
/* Construct and send the request to server */
|
||||||
ListFilesResponse response;
|
|
||||||
pb_istream_t input = pb_istream_from_socket(fd);
|
|
||||||
pb_ostream_t output = pb_ostream_from_socket(fd);
|
|
||||||
uint8_t zero = 0;
|
|
||||||
|
|
||||||
if (path == NULL)
|
|
||||||
{
|
{
|
||||||
request.has_path = false;
|
ListFilesRequest request = {};
|
||||||
}
|
pb_ostream_t output = pb_ostream_from_socket(fd);
|
||||||
else
|
uint8_t zero = 0;
|
||||||
{
|
|
||||||
request.has_path = true;
|
/* In our protocol, path is optional. If it is not given,
|
||||||
if (strlen(path) + 1 > sizeof(request.path))
|
* the server will list the root directory. */
|
||||||
|
if (path == NULL)
|
||||||
{
|
{
|
||||||
fprintf(stderr, "Too long path.\n");
|
request.has_path = false;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
request.has_path = true;
|
||||||
|
if (strlen(path) + 1 > sizeof(request.path))
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Too long path.\n");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
strcpy(request.path, path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Encode the request. It is written to the socket immediately
|
||||||
|
* through our custom stream. */
|
||||||
|
if (!pb_encode(&output, ListFilesRequest_fields, &request))
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&output));
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
strcpy(request.path, path);
|
/* We signal the end of request with a 0 tag. */
|
||||||
|
pb_write(&output, &zero, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!pb_encode(&output, ListFilesRequest_fields, &request))
|
/* Read back the response from server */
|
||||||
{
|
{
|
||||||
fprintf(stderr, "Encoding failed.\n");
|
ListFilesResponse response = {};
|
||||||
return false;
|
pb_istream_t input = pb_istream_from_socket(fd);
|
||||||
}
|
|
||||||
|
/* Give a pointer to our callback function, which will handle the
|
||||||
/* We signal the end of request with a 0 tag. */
|
* filenames as they arrive. */
|
||||||
pb_write(&output, &zero, 1);
|
response.file.funcs.decode = &printfile_callback;
|
||||||
|
|
||||||
response.file.funcs.decode = &printfile_callback;
|
if (!pb_decode(&input, ListFilesResponse_fields, &response))
|
||||||
|
{
|
||||||
if (!pb_decode(&input, ListFilesResponse_fields, &response))
|
fprintf(stderr, "Decode failed: %s\n", PB_GET_ERROR(&input));
|
||||||
{
|
return false;
|
||||||
fprintf(stderr, "Decode failed: %s\n", PB_GET_ERROR(&input));
|
}
|
||||||
return false;
|
|
||||||
}
|
/* If the message from server decodes properly, but directory was
|
||||||
|
* not found on server side, we get path_error == true. */
|
||||||
if (response.path_error)
|
if (response.path_error)
|
||||||
{
|
{
|
||||||
fprintf(stderr, "Server reported error.\n");
|
fprintf(stderr, "Server reported error.\n");
|
||||||
return false;
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
@@ -96,6 +119,7 @@ int main(int argc, char **argv)
|
|||||||
|
|
||||||
sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||||
|
|
||||||
|
/* Connect to server running on localhost:1234 */
|
||||||
memset(&servaddr, 0, sizeof(servaddr));
|
memset(&servaddr, 0, sizeof(servaddr));
|
||||||
servaddr.sin_family = AF_INET;
|
servaddr.sin_family = AF_INET;
|
||||||
servaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
servaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||||
@@ -107,9 +131,11 @@ int main(int argc, char **argv)
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Send the directory listing request */
|
||||||
if (!listdir(sockfd, path))
|
if (!listdir(sockfd, path))
|
||||||
return 2;
|
return 2;
|
||||||
|
|
||||||
|
/* Close connection */
|
||||||
close(sockfd);
|
close(sockfd);
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
|
|||||||
@@ -23,11 +23,16 @@
|
|||||||
#include "fileproto.pb.h"
|
#include "fileproto.pb.h"
|
||||||
#include "common.h"
|
#include "common.h"
|
||||||
|
|
||||||
|
/* This callback function will be called once during the encoding.
|
||||||
|
* It will write out any number of FileInfo entries, without consuming unnecessary memory.
|
||||||
|
* This is accomplished by fetching the filenames one at a time and encoding them
|
||||||
|
* immediately.
|
||||||
|
*/
|
||||||
bool listdir_callback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
|
bool listdir_callback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
|
||||||
{
|
{
|
||||||
DIR *dir = (DIR*) *arg;
|
DIR *dir = (DIR*) *arg;
|
||||||
struct dirent *file;
|
struct dirent *file;
|
||||||
FileInfo fileinfo;
|
FileInfo fileinfo = {};
|
||||||
|
|
||||||
while ((file = readdir(dir)) != NULL)
|
while ((file = readdir(dir)) != NULL)
|
||||||
{
|
{
|
||||||
@@ -35,9 +40,12 @@ bool listdir_callback(pb_ostream_t *stream, const pb_field_t *field, void * cons
|
|||||||
strncpy(fileinfo.name, file->d_name, sizeof(fileinfo.name));
|
strncpy(fileinfo.name, file->d_name, sizeof(fileinfo.name));
|
||||||
fileinfo.name[sizeof(fileinfo.name) - 1] = '\0';
|
fileinfo.name[sizeof(fileinfo.name) - 1] = '\0';
|
||||||
|
|
||||||
|
/* This encodes the header for the field, based on the constant info
|
||||||
|
* from pb_field_t. */
|
||||||
if (!pb_encode_tag_for_field(stream, field))
|
if (!pb_encode_tag_for_field(stream, field))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
|
/* This encodes the data for the field, based on our FileInfo structure. */
|
||||||
if (!pb_encode_submessage(stream, FileInfo_fields, &fileinfo))
|
if (!pb_encode_submessage(stream, FileInfo_fields, &fileinfo))
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -45,43 +53,59 @@ bool listdir_callback(pb_ostream_t *stream, const pb_field_t *field, void * cons
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Handle one arriving client connection.
|
||||||
|
* Clients are expected to send a ListFilesRequest, terminated by a '0'.
|
||||||
|
* Server will respond with a ListFilesResponse message.
|
||||||
|
*/
|
||||||
void handle_connection(int connfd)
|
void handle_connection(int connfd)
|
||||||
{
|
{
|
||||||
ListFilesRequest request;
|
DIR *directory = NULL;
|
||||||
ListFilesResponse response;
|
|
||||||
pb_istream_t input = pb_istream_from_socket(connfd);
|
|
||||||
pb_ostream_t output = pb_ostream_from_socket(connfd);
|
|
||||||
DIR *directory;
|
|
||||||
|
|
||||||
if (!pb_decode(&input, ListFilesRequest_fields, &request))
|
/* Decode the message from the client and open the requested directory. */
|
||||||
{
|
{
|
||||||
printf("Decode failed: %s\n", PB_GET_ERROR(&input));
|
ListFilesRequest request = {};
|
||||||
return;
|
pb_istream_t input = pb_istream_from_socket(connfd);
|
||||||
}
|
|
||||||
|
|
||||||
directory = opendir(request.path);
|
|
||||||
|
|
||||||
printf("Listing directory: %s\n", request.path);
|
|
||||||
|
|
||||||
if (directory == NULL)
|
|
||||||
{
|
|
||||||
perror("opendir");
|
|
||||||
|
|
||||||
response.has_path_error = true;
|
if (!pb_decode(&input, ListFilesRequest_fields, &request))
|
||||||
response.path_error = true;
|
{
|
||||||
response.file.funcs.encode = NULL;
|
printf("Decode failed: %s\n", PB_GET_ERROR(&input));
|
||||||
}
|
return;
|
||||||
else
|
}
|
||||||
{
|
|
||||||
response.has_path_error = false;
|
directory = opendir(request.path);
|
||||||
response.file.funcs.encode = &listdir_callback;
|
printf("Listing directory: %s\n", request.path);
|
||||||
response.file.arg = directory;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!pb_encode(&output, ListFilesResponse_fields, &response))
|
/* List the files in the directory and transmit the response to client */
|
||||||
{
|
{
|
||||||
printf("Encoding failed.\n");
|
ListFilesResponse response = {};
|
||||||
|
pb_ostream_t output = pb_ostream_from_socket(connfd);
|
||||||
|
|
||||||
|
if (directory == NULL)
|
||||||
|
{
|
||||||
|
perror("opendir");
|
||||||
|
|
||||||
|
/* Directory was not found, transmit error status */
|
||||||
|
response.has_path_error = true;
|
||||||
|
response.path_error = true;
|
||||||
|
response.file.funcs.encode = NULL;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* Directory was found, transmit filenames */
|
||||||
|
response.has_path_error = false;
|
||||||
|
response.file.funcs.encode = &listdir_callback;
|
||||||
|
response.file.arg = directory;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!pb_encode(&output, ListFilesResponse_fields, &response))
|
||||||
|
{
|
||||||
|
printf("Encoding failed: %s\n", PB_GET_ERROR(&output));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (directory != NULL)
|
||||||
|
closedir(directory);
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(int argc, char **argv)
|
int main(int argc, char **argv)
|
||||||
@@ -90,8 +114,8 @@ int main(int argc, char **argv)
|
|||||||
struct sockaddr_in servaddr;
|
struct sockaddr_in servaddr;
|
||||||
int reuse = 1;
|
int reuse = 1;
|
||||||
|
|
||||||
|
/* Listen on localhost:1234 for TCP connections */
|
||||||
listenfd = socket(AF_INET, SOCK_STREAM, 0);
|
listenfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||||
|
|
||||||
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
|
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
|
||||||
|
|
||||||
memset(&servaddr, 0, sizeof(servaddr));
|
memset(&servaddr, 0, sizeof(servaddr));
|
||||||
@@ -112,6 +136,7 @@ int main(int argc, char **argv)
|
|||||||
|
|
||||||
for(;;)
|
for(;;)
|
||||||
{
|
{
|
||||||
|
/* Wait for a client */
|
||||||
connfd = accept(listenfd, NULL, NULL);
|
connfd = accept(listenfd, NULL, NULL);
|
||||||
|
|
||||||
if (connfd < 0)
|
if (connfd < 0)
|
||||||
@@ -128,4 +153,6 @@ int main(int argc, char **argv)
|
|||||||
|
|
||||||
close(connfd);
|
close(connfd);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
#!/usr/bin/python
|
#!/usr/bin/python
|
||||||
|
|
||||||
'''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
|
'''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
|
||||||
nanopb_version = "nanopb-0.2.8"
|
nanopb_version = "nanopb-0.2.9.2"
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
@@ -292,29 +292,38 @@ class Field:
|
|||||||
result = None
|
result = None
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def default_decl(self, declaration_only = False):
|
def get_initializer(self, null_init):
|
||||||
'''Return definition for this field's default value.'''
|
'''Return literal expression for this field's default value.'''
|
||||||
if self.default is None:
|
|
||||||
return None
|
if self.pbtype == 'MESSAGE':
|
||||||
|
if null_init:
|
||||||
ctype, default = self.ctype, self.default
|
return '%s_init_zero' % self.ctype
|
||||||
array_decl = ''
|
else:
|
||||||
|
return '%s_init_default' % self.ctype
|
||||||
|
|
||||||
|
if self.default is None or null_init:
|
||||||
|
if self.pbtype == 'STRING':
|
||||||
|
return '""'
|
||||||
|
elif self.pbtype == 'BYTES':
|
||||||
|
return '{0, {0}}'
|
||||||
|
elif self.pbtype == 'ENUM':
|
||||||
|
return '(%s)0' % self.ctype
|
||||||
|
else:
|
||||||
|
return '0'
|
||||||
|
|
||||||
|
default = str(self.default)
|
||||||
|
|
||||||
if self.pbtype == 'STRING':
|
if self.pbtype == 'STRING':
|
||||||
if self.allocation != 'STATIC':
|
default = default.encode('utf-8').encode('string_escape')
|
||||||
return None # Not implemented
|
|
||||||
|
|
||||||
array_decl = '[%d]' % self.max_size
|
|
||||||
default = str(self.default).encode('string_escape')
|
|
||||||
default = default.replace('"', '\\"')
|
default = default.replace('"', '\\"')
|
||||||
default = '"' + default + '"'
|
default = '"' + default + '"'
|
||||||
elif self.pbtype == 'BYTES':
|
elif self.pbtype == 'BYTES':
|
||||||
if self.allocation != 'STATIC':
|
data = default.decode('string_escape')
|
||||||
return None # Not implemented
|
|
||||||
|
|
||||||
data = self.default.decode('string_escape')
|
|
||||||
data = ['0x%02x' % ord(c) for c in data]
|
data = ['0x%02x' % ord(c) for c in data]
|
||||||
default = '{%d, {%s}}' % (len(data), ','.join(data))
|
if len(data) == 0:
|
||||||
|
default = '{0, {0}}'
|
||||||
|
else:
|
||||||
|
default = '{%d, {%s}}' % (len(data), ','.join(data))
|
||||||
elif self.pbtype in ['FIXED32', 'UINT32']:
|
elif self.pbtype in ['FIXED32', 'UINT32']:
|
||||||
default += 'u'
|
default += 'u'
|
||||||
elif self.pbtype in ['FIXED64', 'UINT64']:
|
elif self.pbtype in ['FIXED64', 'UINT64']:
|
||||||
@@ -322,6 +331,25 @@ class Field:
|
|||||||
elif self.pbtype in ['SFIXED64', 'INT64']:
|
elif self.pbtype in ['SFIXED64', 'INT64']:
|
||||||
default += 'll'
|
default += 'll'
|
||||||
|
|
||||||
|
return default
|
||||||
|
|
||||||
|
def default_decl(self, declaration_only = False):
|
||||||
|
'''Return definition for this field's default value.'''
|
||||||
|
if self.default is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
ctype = self.ctype
|
||||||
|
default = self.get_initializer(False)
|
||||||
|
array_decl = ''
|
||||||
|
|
||||||
|
if self.pbtype == 'STRING':
|
||||||
|
if self.allocation != 'STATIC':
|
||||||
|
return None # Not implemented
|
||||||
|
array_decl = '[%d]' % self.max_size
|
||||||
|
elif self.pbtype == 'BYTES':
|
||||||
|
if self.allocation != 'STATIC':
|
||||||
|
return None # Not implemented
|
||||||
|
|
||||||
if declaration_only:
|
if declaration_only:
|
||||||
return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
|
return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
|
||||||
else:
|
else:
|
||||||
@@ -442,7 +470,7 @@ class ExtensionRange(Field):
|
|||||||
|
|
||||||
def tags(self):
|
def tags(self):
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
def encoded_size(self, allmsgs):
|
def encoded_size(self, allmsgs):
|
||||||
# We exclude extensions from the count, because they cannot be known
|
# We exclude extensions from the count, because they cannot be known
|
||||||
# until runtime. Other option would be to return None here, but this
|
# until runtime. Other option would be to return None here, but this
|
||||||
@@ -553,6 +581,34 @@ class Message:
|
|||||||
result += types + '\n'
|
result += types + '\n'
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
def get_initializer(self, null_init):
|
||||||
|
if not self.ordered_fields:
|
||||||
|
return '{0}'
|
||||||
|
|
||||||
|
parts = []
|
||||||
|
for field in self.ordered_fields:
|
||||||
|
if field.allocation == 'STATIC':
|
||||||
|
if field.rules == 'REPEATED':
|
||||||
|
parts.append('0')
|
||||||
|
parts.append('{'
|
||||||
|
+ ', '.join([field.get_initializer(null_init)] * field.max_count)
|
||||||
|
+ '}')
|
||||||
|
elif field.rules == 'OPTIONAL':
|
||||||
|
parts.append('false')
|
||||||
|
parts.append(field.get_initializer(null_init))
|
||||||
|
else:
|
||||||
|
parts.append(field.get_initializer(null_init))
|
||||||
|
elif field.allocation == 'POINTER':
|
||||||
|
if field.rules == 'REPEATED':
|
||||||
|
parts.append('0')
|
||||||
|
parts.append('NULL')
|
||||||
|
elif field.allocation == 'CALLBACK':
|
||||||
|
if field.pbtype == 'EXTENSION':
|
||||||
|
parts.append('NULL')
|
||||||
|
else:
|
||||||
|
parts.append('{{NULL}, NULL}')
|
||||||
|
return '{' + ', '.join(parts) + '}'
|
||||||
|
|
||||||
def default_decl(self, declaration_only = False):
|
def default_decl(self, declaration_only = False):
|
||||||
result = ""
|
result = ""
|
||||||
for field in self.fields:
|
for field in self.fields:
|
||||||
@@ -639,13 +695,17 @@ def parse_file(fdesc, file_options):
|
|||||||
|
|
||||||
for names, message in iterate_messages(fdesc, base_name):
|
for names, message in iterate_messages(fdesc, base_name):
|
||||||
message_options = get_nanopb_suboptions(message, file_options, names)
|
message_options = get_nanopb_suboptions(message, file_options, names)
|
||||||
|
|
||||||
|
if message_options.skip_message:
|
||||||
|
continue
|
||||||
|
|
||||||
messages.append(Message(names, message, message_options))
|
messages.append(Message(names, message, message_options))
|
||||||
for enum in message.enum_type:
|
for enum in message.enum_type:
|
||||||
enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
|
enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
|
||||||
enums.append(Enum(names, enum, enum_options))
|
enums.append(Enum(names, enum, enum_options))
|
||||||
|
|
||||||
for names, extension in iterate_extensions(fdesc, base_name):
|
for names, extension in iterate_extensions(fdesc, base_name):
|
||||||
field_options = get_nanopb_suboptions(extension, file_options, names)
|
field_options = get_nanopb_suboptions(extension, file_options, names + extension.name)
|
||||||
if field_options.type != nanopb_pb2.FT_IGNORE:
|
if field_options.type != nanopb_pb2.FT_IGNORE:
|
||||||
extensions.append(ExtensionField(names, extension, field_options))
|
extensions.append(ExtensionField(names, extension, field_options))
|
||||||
|
|
||||||
@@ -724,7 +784,7 @@ def generate_header(dependencies, headername, enums, messages, extensions, optio
|
|||||||
|
|
||||||
for dependency in dependencies:
|
for dependency in dependencies:
|
||||||
noext = os.path.splitext(dependency)[0]
|
noext = os.path.splitext(dependency)[0]
|
||||||
yield options.genformat % (noext + '.' + options.extension + '.h')
|
yield options.genformat % (noext + options.extension + '.h')
|
||||||
yield '\n'
|
yield '\n'
|
||||||
|
|
||||||
yield '#ifdef __cplusplus\n'
|
yield '#ifdef __cplusplus\n'
|
||||||
@@ -751,6 +811,15 @@ def generate_header(dependencies, headername, enums, messages, extensions, optio
|
|||||||
yield msg.default_decl(True)
|
yield msg.default_decl(True)
|
||||||
yield '\n'
|
yield '\n'
|
||||||
|
|
||||||
|
yield '/* Initializer values for message structs */\n'
|
||||||
|
for msg in messages:
|
||||||
|
identifier = '%s_init_default' % msg.name
|
||||||
|
yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
|
||||||
|
for msg in messages:
|
||||||
|
identifier = '%s_init_zero' % msg.name
|
||||||
|
yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
|
||||||
|
yield '\n'
|
||||||
|
|
||||||
yield '/* Field tags (for use in manual encoding/decoding) */\n'
|
yield '/* Field tags (for use in manual encoding/decoding) */\n'
|
||||||
for msg in sort_dependencies(messages):
|
for msg in sort_dependencies(messages):
|
||||||
for field in msg.fields:
|
for field in msg.fields:
|
||||||
@@ -959,8 +1028,8 @@ optparser = OptionParser(
|
|||||||
"Output will be written to file.pb.h and file.pb.c.")
|
"Output will be written to file.pb.h and file.pb.c.")
|
||||||
optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
|
optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
|
||||||
help="Exclude file from generated #include list.")
|
help="Exclude file from generated #include list.")
|
||||||
optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
|
optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
|
||||||
help="Set extension to use instead of 'pb' for generated files. [default: %default]")
|
help="Set extension to use instead of '.pb' for generated files. [default: %default]")
|
||||||
optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
|
optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
|
||||||
help="Set name of a separate generator options file.")
|
help="Set name of a separate generator options file.")
|
||||||
optparser.add_option("-Q", "--generated-include-format", dest="genformat",
|
optparser.add_option("-Q", "--generated-include-format", dest="genformat",
|
||||||
@@ -1000,29 +1069,38 @@ def process_file(filename, fdesc, options):
|
|||||||
fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
|
fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
|
||||||
|
|
||||||
# Check if there is a separate .options file
|
# Check if there is a separate .options file
|
||||||
|
had_abspath = False
|
||||||
try:
|
try:
|
||||||
optfilename = options.options_file % os.path.splitext(filename)[0]
|
optfilename = options.options_file % os.path.splitext(filename)[0]
|
||||||
except TypeError:
|
except TypeError:
|
||||||
# No %s specified, use the filename as-is
|
# No %s specified, use the filename as-is
|
||||||
optfilename = options.options_file
|
optfilename = options.options_file
|
||||||
|
had_abspath = True
|
||||||
|
|
||||||
if os.path.isfile(optfilename):
|
if os.path.isfile(optfilename):
|
||||||
if options.verbose:
|
if options.verbose:
|
||||||
sys.stderr.write('Reading options from ' + optfilename + '\n')
|
sys.stderr.write('Reading options from ' + optfilename + '\n')
|
||||||
|
|
||||||
Globals.separate_options = read_options_file(open(optfilename, "rU"))
|
Globals.separate_options = read_options_file(open(optfilename, "rU"))
|
||||||
else:
|
else:
|
||||||
|
# If we are given a full filename and it does not exist, give an error.
|
||||||
|
# However, don't give error when we automatically look for .options file
|
||||||
|
# with the same name as .proto.
|
||||||
|
if options.verbose or had_abspath:
|
||||||
|
sys.stderr.write('Options file not found: ' + optfilename)
|
||||||
|
|
||||||
Globals.separate_options = []
|
Globals.separate_options = []
|
||||||
|
|
||||||
Globals.matched_namemasks = set()
|
Globals.matched_namemasks = set()
|
||||||
|
|
||||||
# Parse the file
|
# Parse the file
|
||||||
file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
|
file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
|
||||||
enums, messages, extensions = parse_file(fdesc, file_options)
|
enums, messages, extensions = parse_file(fdesc, file_options)
|
||||||
|
|
||||||
# Decide the file names
|
# Decide the file names
|
||||||
noext = os.path.splitext(filename)[0]
|
noext = os.path.splitext(filename)[0]
|
||||||
headername = noext + '.' + options.extension + '.h'
|
headername = noext + options.extension + '.h'
|
||||||
sourcename = noext + '.' + options.extension + '.c'
|
sourcename = noext + options.extension + '.c'
|
||||||
headerbasename = os.path.basename(headername)
|
headerbasename = os.path.basename(headername)
|
||||||
|
|
||||||
# List of .proto files that should not be included in the C header file
|
# List of .proto files that should not be included in the C header file
|
||||||
|
|||||||
@@ -37,6 +37,9 @@ message NanoPBOptions {
|
|||||||
// Note: this cannot be used on CPUs that break on unaligned
|
// Note: this cannot be used on CPUs that break on unaligned
|
||||||
// accesses to variables.
|
// accesses to variables.
|
||||||
optional bool packed_struct = 5 [default = false];
|
optional bool packed_struct = 5 [default = false];
|
||||||
|
|
||||||
|
// Skip this message
|
||||||
|
optional bool skip_message = 6 [default = false];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extensions to protoc 'Descriptor' type in order to define options
|
// Extensions to protoc 'Descriptor' type in order to define options
|
||||||
|
|||||||
6
pb.h
6
pb.h
@@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
/* Version of the nanopb library. Just in case you want to check it in
|
/* Version of the nanopb library. Just in case you want to check it in
|
||||||
* your own program. */
|
* your own program. */
|
||||||
#define NANOPB_VERSION nanopb-0.2.8
|
#define NANOPB_VERSION nanopb-0.2.9.2
|
||||||
|
|
||||||
/* Include all the system headers needed by nanopb. You will need the
|
/* Include all the system headers needed by nanopb. You will need the
|
||||||
* definitions of the following:
|
* definitions of the following:
|
||||||
@@ -80,8 +80,8 @@
|
|||||||
# define PB_PACKED_STRUCT_START
|
# define PB_PACKED_STRUCT_START
|
||||||
# define PB_PACKED_STRUCT_END
|
# define PB_PACKED_STRUCT_END
|
||||||
# define pb_packed __attribute__((packed))
|
# define pb_packed __attribute__((packed))
|
||||||
#elif defined(__ICCARM__)
|
#elif defined(__ICCARM__) || defined(__CC_ARM)
|
||||||
/* For IAR ARM compiler */
|
/* For IAR ARM and Keil MDK-ARM compilers */
|
||||||
# define PB_PACKED_STRUCT_START _Pragma("pack(push, 1)")
|
# define PB_PACKED_STRUCT_START _Pragma("pack(push, 1)")
|
||||||
# define PB_PACKED_STRUCT_END _Pragma("pack(pop)")
|
# define PB_PACKED_STRUCT_END _Pragma("pack(pop)")
|
||||||
# define pb_packed
|
# define pb_packed
|
||||||
|
|||||||
193
pb_decode.c
193
pb_decode.c
@@ -42,6 +42,7 @@ static bool checkreturn pb_field_find(pb_field_iterator_t *iter, uint32_t tag);
|
|||||||
static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter);
|
static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter);
|
||||||
static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter);
|
static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter);
|
||||||
static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter);
|
static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iterator_t *iter);
|
||||||
|
static void iter_from_extension(pb_field_iterator_t *iter, pb_extension_t *extension);
|
||||||
static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type);
|
static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type);
|
||||||
static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iterator_t *iter);
|
static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iterator_t *iter);
|
||||||
static bool checkreturn find_extension_field(pb_field_iterator_t *iter);
|
static bool checkreturn find_extension_field(pb_field_iterator_t *iter);
|
||||||
@@ -57,6 +58,11 @@ static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t
|
|||||||
static bool checkreturn pb_skip_varint(pb_istream_t *stream);
|
static bool checkreturn pb_skip_varint(pb_istream_t *stream);
|
||||||
static bool checkreturn pb_skip_string(pb_istream_t *stream);
|
static bool checkreturn pb_skip_string(pb_istream_t *stream);
|
||||||
|
|
||||||
|
#ifdef PB_ENABLE_MALLOC
|
||||||
|
static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size);
|
||||||
|
static void pb_release_single_field(const pb_field_iterator_t *iter);
|
||||||
|
#endif
|
||||||
|
|
||||||
/* --- Function pointers to field decoders ---
|
/* --- Function pointers to field decoders ---
|
||||||
* Order in the array must match pb_action_t LTYPE numbering.
|
* Order in the array must match pb_action_t LTYPE numbering.
|
||||||
*/
|
*/
|
||||||
@@ -471,35 +477,36 @@ static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t
|
|||||||
#ifdef PB_ENABLE_MALLOC
|
#ifdef PB_ENABLE_MALLOC
|
||||||
/* Allocate storage for the field and store the pointer at iter->pData.
|
/* Allocate storage for the field and store the pointer at iter->pData.
|
||||||
* array_size is the number of entries to reserve in an array.
|
* array_size is the number of entries to reserve in an array.
|
||||||
|
* Zero size is not allowed, use pb_free() for releasing.
|
||||||
*/
|
*/
|
||||||
static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size)
|
static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size)
|
||||||
{
|
{
|
||||||
void *ptr = *(void**)pData;
|
void *ptr = *(void**)pData;
|
||||||
|
|
||||||
/* Check for multiplication overflows. */
|
if (data_size == 0 || array_size == 0)
|
||||||
size_t size = 0;
|
PB_RETURN_ERROR(stream, "invalid size");
|
||||||
if (data_size > 0 && array_size > 0)
|
|
||||||
|
/* Check for multiplication overflows.
|
||||||
|
* This code avoids the costly division if the sizes are small enough.
|
||||||
|
* Multiplication is safe as long as only half of bits are set
|
||||||
|
* in either multiplicand.
|
||||||
|
*/
|
||||||
{
|
{
|
||||||
/* Avoid the costly division if the sizes are small enough.
|
|
||||||
* Multiplication is safe as long as only half of bits are set
|
|
||||||
* in either multiplicand.
|
|
||||||
*/
|
|
||||||
const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4);
|
const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4);
|
||||||
if (data_size >= check_limit || array_size >= check_limit)
|
if (data_size >= check_limit || array_size >= check_limit)
|
||||||
{
|
{
|
||||||
if (SIZE_MAX / array_size < data_size)
|
const size_t size_max = (size_t)-1;
|
||||||
|
if (size_max / array_size < data_size)
|
||||||
{
|
{
|
||||||
PB_RETURN_ERROR(stream, "size too large");
|
PB_RETURN_ERROR(stream, "size too large");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
size = array_size * data_size;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Allocate new or expand previous allocation */
|
/* Allocate new or expand previous allocation */
|
||||||
/* Note: on failure the old pointer will remain in the structure,
|
/* Note: on failure the old pointer will remain in the structure,
|
||||||
* the message must be freed by caller also on error return. */
|
* the message must be freed by caller also on error return. */
|
||||||
ptr = pb_realloc(ptr, size);
|
ptr = pb_realloc(ptr, array_size * data_size);
|
||||||
if (ptr == NULL)
|
if (ptr == NULL)
|
||||||
PB_RETURN_ERROR(stream, "realloc failed");
|
PB_RETURN_ERROR(stream, "realloc failed");
|
||||||
|
|
||||||
@@ -539,6 +546,13 @@ static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_
|
|||||||
{
|
{
|
||||||
case PB_HTYPE_REQUIRED:
|
case PB_HTYPE_REQUIRED:
|
||||||
case PB_HTYPE_OPTIONAL:
|
case PB_HTYPE_OPTIONAL:
|
||||||
|
if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&
|
||||||
|
*(void**)iter->pData != NULL)
|
||||||
|
{
|
||||||
|
/* Duplicate field, have to release the old allocation first. */
|
||||||
|
pb_release_single_field(iter);
|
||||||
|
}
|
||||||
|
|
||||||
if (PB_LTYPE(type) == PB_LTYPE_STRING ||
|
if (PB_LTYPE(type) == PB_LTYPE_STRING ||
|
||||||
PB_LTYPE(type) == PB_LTYPE_BYTES)
|
PB_LTYPE(type) == PB_LTYPE_BYTES)
|
||||||
{
|
{
|
||||||
@@ -683,6 +697,19 @@ static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_t
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static void iter_from_extension(pb_field_iterator_t *iter, pb_extension_t *extension)
|
||||||
|
{
|
||||||
|
const pb_field_t *field = (const pb_field_t*)extension->type->arg;
|
||||||
|
|
||||||
|
iter->start = field;
|
||||||
|
iter->pos = field;
|
||||||
|
iter->field_index = 0;
|
||||||
|
iter->required_field_index = 0;
|
||||||
|
iter->dest_struct = extension->dest;
|
||||||
|
iter->pData = extension->dest;
|
||||||
|
iter->pSize = &extension->found;
|
||||||
|
}
|
||||||
|
|
||||||
/* Default handler for extension fields. Expects a pb_field_t structure
|
/* Default handler for extension fields. Expects a pb_field_t structure
|
||||||
* in extension->type->arg. */
|
* in extension->type->arg. */
|
||||||
static bool checkreturn default_extension_decoder(pb_istream_t *stream,
|
static bool checkreturn default_extension_decoder(pb_istream_t *stream,
|
||||||
@@ -694,14 +721,7 @@ static bool checkreturn default_extension_decoder(pb_istream_t *stream,
|
|||||||
if (field->tag != tag)
|
if (field->tag != tag)
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
iter.start = field;
|
iter_from_extension(&iter, extension);
|
||||||
iter.pos = field;
|
|
||||||
iter.field_index = 0;
|
|
||||||
iter.required_field_index = 0;
|
|
||||||
iter.dest_struct = extension->dest;
|
|
||||||
iter.pData = extension->dest;
|
|
||||||
iter.pSize = &extension->found;
|
|
||||||
|
|
||||||
return decode_field(stream, wire_type, &iter);
|
return decode_field(stream, wire_type, &iter);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -938,57 +958,91 @@ bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *
|
|||||||
}
|
}
|
||||||
|
|
||||||
#ifdef PB_ENABLE_MALLOC
|
#ifdef PB_ENABLE_MALLOC
|
||||||
|
static void pb_release_single_field(const pb_field_iterator_t *iter)
|
||||||
|
{
|
||||||
|
pb_type_t type;
|
||||||
|
type = iter->pos->type;
|
||||||
|
|
||||||
|
/* Release anything contained inside an extension or submsg.
|
||||||
|
* This has to be done even if the submsg itself is statically
|
||||||
|
* allocated. */
|
||||||
|
if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
|
||||||
|
{
|
||||||
|
/* Release fields from all extensions in the linked list */
|
||||||
|
pb_extension_t *ext = *(pb_extension_t**)iter->pData;
|
||||||
|
while (ext != NULL)
|
||||||
|
{
|
||||||
|
pb_field_iterator_t ext_iter;
|
||||||
|
iter_from_extension(&ext_iter, ext);
|
||||||
|
pb_release_single_field(&ext_iter);
|
||||||
|
ext = ext->next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)
|
||||||
|
{
|
||||||
|
/* Release fields in submessage or submsg array */
|
||||||
|
void *pItem = iter->pData;
|
||||||
|
pb_size_t count = 1;
|
||||||
|
|
||||||
|
if (PB_ATYPE(type) == PB_ATYPE_POINTER)
|
||||||
|
{
|
||||||
|
pItem = *(void**)iter->pData;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
|
||||||
|
{
|
||||||
|
count = *(pb_size_t*)iter->pSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pItem)
|
||||||
|
{
|
||||||
|
while (count--)
|
||||||
|
{
|
||||||
|
pb_release((const pb_field_t*)iter->pos->ptr, pItem);
|
||||||
|
pItem = (uint8_t*)pItem + iter->pos->data_size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (PB_ATYPE(type) == PB_ATYPE_POINTER)
|
||||||
|
{
|
||||||
|
if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&
|
||||||
|
(PB_LTYPE(type) == PB_LTYPE_STRING ||
|
||||||
|
PB_LTYPE(type) == PB_LTYPE_BYTES))
|
||||||
|
{
|
||||||
|
/* Release entries in repeated string or bytes array */
|
||||||
|
void **pItem = *(void***)iter->pData;
|
||||||
|
pb_size_t count = *(pb_size_t*)iter->pSize;
|
||||||
|
while (count--)
|
||||||
|
{
|
||||||
|
pb_free(*pItem);
|
||||||
|
*pItem++ = NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
|
||||||
|
{
|
||||||
|
/* We are going to release the array, so set the size to 0 */
|
||||||
|
*(pb_size_t*)iter->pSize = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Release main item */
|
||||||
|
pb_free(*(void**)iter->pData);
|
||||||
|
*(void**)iter->pData = NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void pb_release(const pb_field_t fields[], void *dest_struct)
|
void pb_release(const pb_field_t fields[], void *dest_struct)
|
||||||
{
|
{
|
||||||
pb_field_iterator_t iter;
|
pb_field_iterator_t iter;
|
||||||
pb_field_init(&iter, fields, dest_struct);
|
pb_field_init(&iter, fields, dest_struct);
|
||||||
|
|
||||||
|
if (iter.pos->tag == 0)
|
||||||
|
return; /* Empty message type */
|
||||||
|
|
||||||
do
|
do
|
||||||
{
|
{
|
||||||
pb_type_t type;
|
pb_release_single_field(&iter);
|
||||||
type = iter.pos->type;
|
|
||||||
|
|
||||||
/* Avoid crash on empty message types (zero fields) */
|
|
||||||
if (iter.pos->tag == 0)
|
|
||||||
continue;
|
|
||||||
|
|
||||||
if (PB_ATYPE(type) == PB_ATYPE_POINTER)
|
|
||||||
{
|
|
||||||
if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&
|
|
||||||
(PB_LTYPE(type) == PB_LTYPE_STRING ||
|
|
||||||
PB_LTYPE(type) == PB_LTYPE_BYTES))
|
|
||||||
{
|
|
||||||
/* Release entries in repeated string or bytes array */
|
|
||||||
void **pItem = *(void***)iter.pData;
|
|
||||||
size_t count = *(size_t*)iter.pSize;
|
|
||||||
while (count--)
|
|
||||||
{
|
|
||||||
pb_free(*pItem);
|
|
||||||
*pItem++ = NULL;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)
|
|
||||||
{
|
|
||||||
/* Release fields in submessages */
|
|
||||||
void *pItem = *(void**)iter.pData;
|
|
||||||
size_t count = (pItem ? 1 : 0);
|
|
||||||
|
|
||||||
if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
|
|
||||||
{
|
|
||||||
count = *(size_t*)iter.pSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
while (count--)
|
|
||||||
{
|
|
||||||
pb_release((const pb_field_t*)iter.pos->ptr, pItem);
|
|
||||||
pItem = (uint8_t*)pItem + iter.pos->data_size;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Release main item */
|
|
||||||
pb_free(*(void**)iter.pData);
|
|
||||||
*(void**)iter.pData = NULL;
|
|
||||||
}
|
|
||||||
} while (pb_field_next(&iter));
|
} while (pb_field_next(&iter));
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@@ -1116,29 +1170,35 @@ static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *f
|
|||||||
static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
|
static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
|
||||||
{
|
{
|
||||||
uint32_t size;
|
uint32_t size;
|
||||||
|
size_t alloc_size;
|
||||||
pb_bytes_array_t *bdest;
|
pb_bytes_array_t *bdest;
|
||||||
|
|
||||||
if (!pb_decode_varint32(stream, &size))
|
if (!pb_decode_varint32(stream, &size))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
|
alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size);
|
||||||
|
if (size > alloc_size)
|
||||||
|
PB_RETURN_ERROR(stream, "size too large");
|
||||||
|
|
||||||
if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
|
if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
|
||||||
{
|
{
|
||||||
#ifndef PB_ENABLE_MALLOC
|
#ifndef PB_ENABLE_MALLOC
|
||||||
PB_RETURN_ERROR(stream, "no malloc support");
|
PB_RETURN_ERROR(stream, "no malloc support");
|
||||||
#else
|
#else
|
||||||
if (!allocate_field(stream, dest, PB_BYTES_ARRAY_T_ALLOCSIZE(size), 1))
|
if (!allocate_field(stream, dest, alloc_size, 1))
|
||||||
return false;
|
return false;
|
||||||
bdest = *(pb_bytes_array_t**)dest;
|
bdest = *(pb_bytes_array_t**)dest;
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if (PB_BYTES_ARRAY_T_ALLOCSIZE(size) > field->data_size)
|
if (alloc_size > field->data_size)
|
||||||
PB_RETURN_ERROR(stream, "bytes overflow");
|
PB_RETURN_ERROR(stream, "bytes overflow");
|
||||||
bdest = (pb_bytes_array_t*)dest;
|
bdest = (pb_bytes_array_t*)dest;
|
||||||
}
|
}
|
||||||
|
|
||||||
bdest->size = size;
|
bdest->size = size;
|
||||||
|
|
||||||
return pb_read(stream, bdest->bytes, size);
|
return pb_read(stream, bdest->bytes, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1153,6 +1213,9 @@ static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *fi
|
|||||||
/* Space for null terminator */
|
/* Space for null terminator */
|
||||||
alloc_size = size + 1;
|
alloc_size = size + 1;
|
||||||
|
|
||||||
|
if (alloc_size < size)
|
||||||
|
PB_RETURN_ERROR(stream, "size too large");
|
||||||
|
|
||||||
if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
|
if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
|
||||||
{
|
{
|
||||||
#ifndef PB_ENABLE_MALLOC
|
#ifndef PB_ENABLE_MALLOC
|
||||||
|
|||||||
@@ -57,6 +57,7 @@ if not env.GetOption('clean'):
|
|||||||
if not stdbool or not stdint or not stddef or not string:
|
if not stdbool or not stdint or not stddef or not string:
|
||||||
conf.env.Append(CPPDEFINES = {'PB_SYSTEM_HEADER': '\\"pb_syshdr.h\\"'})
|
conf.env.Append(CPPDEFINES = {'PB_SYSTEM_HEADER': '\\"pb_syshdr.h\\"'})
|
||||||
conf.env.Append(CPPPATH = "#../extra")
|
conf.env.Append(CPPPATH = "#../extra")
|
||||||
|
conf.env.Append(SYSHDR = '\\"pb_syshdr.h\\"')
|
||||||
|
|
||||||
if stdbool: conf.env.Append(CPPDEFINES = {'HAVE_STDBOOL_H': 1})
|
if stdbool: conf.env.Append(CPPDEFINES = {'HAVE_STDBOOL_H': 1})
|
||||||
if stdint: conf.env.Append(CPPDEFINES = {'HAVE_STDINT_H': 1})
|
if stdint: conf.env.Append(CPPDEFINES = {'HAVE_STDINT_H': 1})
|
||||||
@@ -101,7 +102,7 @@ if 'gcc' in env['CC']:
|
|||||||
# GNU Compiler Collection
|
# GNU Compiler Collection
|
||||||
|
|
||||||
# Debug info, warnings as errors
|
# Debug info, warnings as errors
|
||||||
env.Append(CFLAGS = '-ansi -pedantic -g -Wall -Werror -fprofile-arcs -ftest-coverage -fstack-protector-all')
|
env.Append(CFLAGS = '-ansi -pedantic -g -Wall -Werror -fprofile-arcs -ftest-coverage ')
|
||||||
env.Append(CORECFLAGS = '-Wextra')
|
env.Append(CORECFLAGS = '-Wextra')
|
||||||
env.Append(LINKFLAGS = '-g --coverage')
|
env.Append(LINKFLAGS = '-g --coverage')
|
||||||
|
|
||||||
@@ -135,12 +136,18 @@ elif 'g++' in env['CXX'] or 'gcc' in env['CXX']:
|
|||||||
env.Append(CXXFLAGS = '-g -Wall -Werror -Wextra -Wno-missing-field-initializers')
|
env.Append(CXXFLAGS = '-g -Wall -Werror -Wextra -Wno-missing-field-initializers')
|
||||||
elif 'cl' in env['CXX']:
|
elif 'cl' in env['CXX']:
|
||||||
env.Append(CXXFLAGS = '/Zi /W2 /WX')
|
env.Append(CXXFLAGS = '/Zi /W2 /WX')
|
||||||
|
|
||||||
# Now include the SConscript files from all subdirectories
|
# Now include the SConscript files from all subdirectories
|
||||||
import os.path
|
import os.path
|
||||||
env['VARIANT_DIR'] = 'build'
|
env['VARIANT_DIR'] = 'build'
|
||||||
env['BUILD'] = '#' + env['VARIANT_DIR']
|
env['BUILD'] = '#' + env['VARIANT_DIR']
|
||||||
env['COMMON'] = '#' + env['VARIANT_DIR'] + '/common'
|
env['COMMON'] = '#' + env['VARIANT_DIR'] + '/common'
|
||||||
for subdir in Glob('*/SConscript'):
|
|
||||||
|
# Include common/SConscript first to make sure its exports are available
|
||||||
|
# to other SConscripts.
|
||||||
|
SConscript("common/SConscript", exports = 'env', variant_dir = env['VARIANT_DIR'] + '/common')
|
||||||
|
|
||||||
|
for subdir in Glob('*/SConscript') + Glob('regression/*/SConscript'):
|
||||||
|
if str(subdir).startswith("common"): continue
|
||||||
SConscript(subdir, exports = 'env', variant_dir = env['VARIANT_DIR'] + '/' + os.path.dirname(str(subdir)))
|
SConscript(subdir, exports = 'env', variant_dir = env['VARIANT_DIR'] + '/' + os.path.dirname(str(subdir)))
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,8 @@
|
|||||||
the decoding and checks the fields. */
|
the decoding and checks the fields. */
|
||||||
bool check_alltypes(pb_istream_t *stream, int mode)
|
bool check_alltypes(pb_istream_t *stream, int mode)
|
||||||
{
|
{
|
||||||
AllTypes alltypes;
|
/* Uses _init_default to just make sure that it works. */
|
||||||
|
AllTypes alltypes = AllTypes_init_default;
|
||||||
|
|
||||||
/* Fill with garbage to better detect initialization errors */
|
/* Fill with garbage to better detect initialization errors */
|
||||||
memset(&alltypes, 0xAA, sizeof(alltypes));
|
memset(&alltypes, 0xAA, sizeof(alltypes));
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ int main(int argc, char **argv)
|
|||||||
int mode = (argc > 1) ? atoi(argv[1]) : 0;
|
int mode = (argc > 1) ? atoi(argv[1]) : 0;
|
||||||
|
|
||||||
/* Initialize the structure with constants */
|
/* Initialize the structure with constants */
|
||||||
AllTypes alltypes = {0};
|
AllTypes alltypes = AllTypes_init_zero;
|
||||||
|
|
||||||
alltypes.req_int32 = -1001;
|
alltypes.req_int32 = -1001;
|
||||||
alltypes.req_int64 = -1002;
|
alltypes.req_int64 = -1002;
|
||||||
|
|||||||
@@ -1,30 +1,20 @@
|
|||||||
# Encode the AllTypes message using pointers for all fields, and verify the
|
# Encode the AllTypes message using pointers for all fields, and verify the
|
||||||
# output against the normal AllTypes test case.
|
# output against the normal AllTypes test case.
|
||||||
|
|
||||||
Import("env")
|
Import("env", "malloc_env")
|
||||||
|
|
||||||
# We need our own pb_decode.o for the malloc support
|
|
||||||
env = env.Clone()
|
|
||||||
env.Append(CPPDEFINES = {'PB_ENABLE_MALLOC': 1});
|
|
||||||
|
|
||||||
# Disable libmudflap, because it will confuse valgrind
|
|
||||||
# and other memory leak detection tools.
|
|
||||||
if '-fmudflap' in env["CCFLAGS"]:
|
|
||||||
env["CCFLAGS"].remove("-fmudflap")
|
|
||||||
env["LINKFLAGS"].remove("-fmudflap")
|
|
||||||
env["LIBS"].remove("mudflap")
|
|
||||||
|
|
||||||
strict = env.Clone()
|
|
||||||
strict.Append(CFLAGS = strict['CORECFLAGS'])
|
|
||||||
strict.Object("pb_decode_with_malloc.o", "$NANOPB/pb_decode.c")
|
|
||||||
strict.Object("pb_encode_with_malloc.o", "$NANOPB/pb_encode.c")
|
|
||||||
|
|
||||||
c = Copy("$TARGET", "$SOURCE")
|
c = Copy("$TARGET", "$SOURCE")
|
||||||
env.Command("alltypes.proto", "#alltypes/alltypes.proto", c)
|
env.Command("alltypes.proto", "#alltypes/alltypes.proto", c)
|
||||||
|
|
||||||
env.NanopbProto(["alltypes", "alltypes.options"])
|
env.NanopbProto(["alltypes", "alltypes.options"])
|
||||||
enc = env.Program(["encode_alltypes_pointer.c", "alltypes.pb.c", "pb_encode_with_malloc.o"])
|
enc = malloc_env.Program(["encode_alltypes_pointer.c",
|
||||||
dec = env.Program(["decode_alltypes_pointer.c", "alltypes.pb.c", "pb_decode_with_malloc.o"])
|
"alltypes.pb.c",
|
||||||
|
"$COMMON/pb_encode_with_malloc.o",
|
||||||
|
"$COMMON/malloc_wrappers.o"])
|
||||||
|
dec = malloc_env.Program(["decode_alltypes_pointer.c",
|
||||||
|
"alltypes.pb.c",
|
||||||
|
"$COMMON/pb_decode_with_malloc.o",
|
||||||
|
"$COMMON/malloc_wrappers.o"])
|
||||||
|
|
||||||
# Encode and compare results to non-pointer alltypes test case
|
# Encode and compare results to non-pointer alltypes test case
|
||||||
env.RunTest(enc)
|
env.RunTest(enc)
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
bool print_person(pb_istream_t *stream)
|
bool print_person(pb_istream_t *stream)
|
||||||
{
|
{
|
||||||
int i;
|
int i;
|
||||||
Person person;
|
Person person = Person_init_zero;
|
||||||
|
|
||||||
if (!pb_decode(stream, Person_fields, &person))
|
if (!pb_decode(stream, Person_fields, &person))
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
bool print_person(pb_istream_t *stream)
|
bool print_person(pb_istream_t *stream)
|
||||||
{
|
{
|
||||||
int i;
|
int i;
|
||||||
Person person;
|
Person person = Person_init_zero;
|
||||||
|
|
||||||
if (!pb_decode(stream, Person_fields, &person))
|
if (!pb_decode(stream, Person_fields, &person))
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ env.NanopbProto("unittestproto")
|
|||||||
# Protocol definitions for basic_buffer/stream tests
|
# Protocol definitions for basic_buffer/stream tests
|
||||||
env.NanopbProto("person")
|
env.NanopbProto("person")
|
||||||
|
|
||||||
|
#--------------------------------------------
|
||||||
# Binaries of the pb_decode.c and pb_encode.c
|
# Binaries of the pb_decode.c and pb_encode.c
|
||||||
# These are built using more strict warning flags.
|
# These are built using more strict warning flags.
|
||||||
strict = env.Clone()
|
strict = env.Clone()
|
||||||
@@ -15,3 +16,31 @@ strict.Append(CFLAGS = strict['CORECFLAGS'])
|
|||||||
strict.Object("pb_decode.o", "$NANOPB/pb_decode.c")
|
strict.Object("pb_decode.o", "$NANOPB/pb_decode.c")
|
||||||
strict.Object("pb_encode.o", "$NANOPB/pb_encode.c")
|
strict.Object("pb_encode.o", "$NANOPB/pb_encode.c")
|
||||||
|
|
||||||
|
#-----------------------------------------------
|
||||||
|
# Binaries of pb_decode etc. with malloc support
|
||||||
|
# Uses malloc_wrappers.c to count allocations.
|
||||||
|
malloc_env = env.Clone()
|
||||||
|
malloc_env.Append(CPPDEFINES = {'PB_ENABLE_MALLOC': 1,
|
||||||
|
'PB_SYSTEM_HEADER': '\\"malloc_wrappers_syshdr.h\\"'})
|
||||||
|
malloc_env.Append(CPPPATH = ["$COMMON"])
|
||||||
|
|
||||||
|
if 'SYSHDR' in malloc_env:
|
||||||
|
malloc_env.Append(CPPDEFINES = {'PB_OLD_SYSHDR': malloc_env['SYSHDR']})
|
||||||
|
|
||||||
|
# Disable libmudflap, because it will confuse valgrind
|
||||||
|
# and other memory leak detection tools.
|
||||||
|
if '-fmudflap' in env["CCFLAGS"]:
|
||||||
|
malloc_env["CCFLAGS"].remove("-fmudflap")
|
||||||
|
malloc_env["LINKFLAGS"].remove("-fmudflap")
|
||||||
|
malloc_env["LIBS"].remove("mudflap")
|
||||||
|
|
||||||
|
malloc_strict = malloc_env.Clone()
|
||||||
|
malloc_strict.Append(CFLAGS = malloc_strict['CORECFLAGS'])
|
||||||
|
malloc_strict.Object("pb_decode_with_malloc.o", "$NANOPB/pb_decode.c")
|
||||||
|
malloc_strict.Object("pb_encode_with_malloc.o", "$NANOPB/pb_encode.c")
|
||||||
|
|
||||||
|
malloc_env.Object("malloc_wrappers.o", "malloc_wrappers.c")
|
||||||
|
malloc_env.Depends("$NANOPB/pb.h", ["malloc_wrappers_syshdr.h", "malloc_wrappers.h"])
|
||||||
|
|
||||||
|
Export("malloc_env")
|
||||||
|
|
||||||
|
|||||||
54
tests/common/malloc_wrappers.c
Normal file
54
tests/common/malloc_wrappers.c
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
#include "malloc_wrappers.h"
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <assert.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
static size_t alloc_count = 0;
|
||||||
|
|
||||||
|
/* Allocate memory and place check values before and after. */
|
||||||
|
void* malloc_with_check(size_t size)
|
||||||
|
{
|
||||||
|
size_t size32 = (size + 3) / 4 + 3;
|
||||||
|
uint32_t *buf = malloc(size32 * sizeof(uint32_t));
|
||||||
|
buf[0] = size32;
|
||||||
|
buf[1] = 0xDEADBEEF;
|
||||||
|
buf[size32 - 1] = 0xBADBAD;
|
||||||
|
return buf + 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Free memory allocated with malloc_with_check() and do the checks. */
|
||||||
|
void free_with_check(void *mem)
|
||||||
|
{
|
||||||
|
uint32_t *buf = (uint32_t*)mem - 2;
|
||||||
|
assert(buf[1] == 0xDEADBEEF);
|
||||||
|
assert(buf[buf[0] - 1] == 0xBADBAD);
|
||||||
|
free(buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Track memory usage */
|
||||||
|
void* counting_realloc(void *ptr, size_t size)
|
||||||
|
{
|
||||||
|
/* Don't allocate crazy amounts of RAM when fuzzing */
|
||||||
|
if (size > 1000000)
|
||||||
|
return NULL;
|
||||||
|
|
||||||
|
if (!ptr && size)
|
||||||
|
alloc_count++;
|
||||||
|
|
||||||
|
return realloc(ptr, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
void counting_free(void *ptr)
|
||||||
|
{
|
||||||
|
if (ptr)
|
||||||
|
{
|
||||||
|
assert(alloc_count > 0);
|
||||||
|
alloc_count--;
|
||||||
|
free(ptr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t get_alloc_count()
|
||||||
|
{
|
||||||
|
return alloc_count;
|
||||||
|
}
|
||||||
7
tests/common/malloc_wrappers.h
Normal file
7
tests/common/malloc_wrappers.h
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
void* malloc_with_check(size_t size);
|
||||||
|
void free_with_check(void *mem);
|
||||||
|
void* counting_realloc(void *ptr, size_t size);
|
||||||
|
void counting_free(void *ptr);
|
||||||
|
size_t get_alloc_count();
|
||||||
15
tests/common/malloc_wrappers_syshdr.h
Normal file
15
tests/common/malloc_wrappers_syshdr.h
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
/* This is just a wrapper in order to get our own malloc wrappers into nanopb core. */
|
||||||
|
|
||||||
|
#define pb_realloc(ptr,size) counting_realloc(ptr,size)
|
||||||
|
#define pb_free(ptr) counting_free(ptr)
|
||||||
|
|
||||||
|
#ifdef PB_OLD_SYSHDR
|
||||||
|
#include PB_OLD_SYSHDR
|
||||||
|
#else
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <string.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include <malloc_wrappers.h>
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
/* This includes the whole .c file to get access to static functions. */
|
/* This includes the whole .c file to get access to static functions. */
|
||||||
|
#define PB_ENABLE_MALLOC
|
||||||
#include "pb_decode.c"
|
#include "pb_decode.c"
|
||||||
|
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
@@ -299,6 +300,28 @@ int main()
|
|||||||
dest.submsg.data_count == 5)
|
dest.submsg.data_count == 5)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_istream_t s = {0};
|
||||||
|
void *data = NULL;
|
||||||
|
|
||||||
|
COMMENT("Testing allocate_field")
|
||||||
|
TEST(allocate_field(&s, &data, 10, 10) && data != NULL);
|
||||||
|
TEST(allocate_field(&s, &data, 10, 20) && data != NULL);
|
||||||
|
|
||||||
|
{
|
||||||
|
void *oldvalue = data;
|
||||||
|
size_t very_big = (size_t)-1;
|
||||||
|
size_t somewhat_big = very_big / 2 + 1;
|
||||||
|
size_t not_so_big = (size_t)1 << (4 * sizeof(size_t));
|
||||||
|
|
||||||
|
TEST(!allocate_field(&s, &data, very_big, 2) && data == oldvalue);
|
||||||
|
TEST(!allocate_field(&s, &data, somewhat_big, 2) && data == oldvalue);
|
||||||
|
TEST(!allocate_field(&s, &data, not_so_big, not_so_big) && data == oldvalue);
|
||||||
|
}
|
||||||
|
|
||||||
|
pb_free(data);
|
||||||
|
}
|
||||||
|
|
||||||
if (status != 0)
|
if (status != 0)
|
||||||
fprintf(stdout, "\n\nSome tests FAILED!\n");
|
fprintf(stdout, "\n\nSome tests FAILED!\n");
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ extend AllTypes {
|
|||||||
message ExtensionMessage {
|
message ExtensionMessage {
|
||||||
extend AllTypes {
|
extend AllTypes {
|
||||||
optional ExtensionMessage AllTypes_extensionfield2 = 254;
|
optional ExtensionMessage AllTypes_extensionfield2 = 254;
|
||||||
required ExtensionMessage AllTypes_extensionfield3 = 253;
|
|
||||||
repeated ExtensionMessage AllTypes_extensionfield4 = 252;
|
repeated ExtensionMessage AllTypes_extensionfield4 = 252;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
34
tests/fuzztest/SConscript
Normal file
34
tests/fuzztest/SConscript
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
# Run a fuzz test to verify robustness against corrupted/malicious data.
|
||||||
|
|
||||||
|
Import("env", "malloc_env")
|
||||||
|
|
||||||
|
# We want both pointer and static versions of the AllTypes message
|
||||||
|
# Prefix them with package name.
|
||||||
|
env.Command("alltypes_static.proto", "#alltypes/alltypes.proto",
|
||||||
|
lambda target, source, env:
|
||||||
|
open(str(target[0]), 'w').write("package alltypes_static;\n"
|
||||||
|
+ open(str(source[0])).read()))
|
||||||
|
env.Command("alltypes_pointer.proto", "#alltypes/alltypes.proto",
|
||||||
|
lambda target, source, env:
|
||||||
|
open(str(target[0]), 'w').write("package alltypes_pointer;\n"
|
||||||
|
+ open(str(source[0])).read()))
|
||||||
|
|
||||||
|
p1 = env.NanopbProto(["alltypes_pointer", "alltypes_pointer.options"])
|
||||||
|
p2 = env.NanopbProto(["alltypes_static", "alltypes_static.options"])
|
||||||
|
fuzz = malloc_env.Program(["fuzztest.c",
|
||||||
|
"alltypes_pointer.pb.c",
|
||||||
|
"alltypes_static.pb.c",
|
||||||
|
"$COMMON/pb_encode_with_malloc.o",
|
||||||
|
"$COMMON/pb_decode_with_malloc.o",
|
||||||
|
"$COMMON/malloc_wrappers.o"])
|
||||||
|
|
||||||
|
env.RunTest(fuzz)
|
||||||
|
|
||||||
|
fuzzstub = malloc_env.Program(["fuzzstub.c",
|
||||||
|
"alltypes_pointer.pb.c",
|
||||||
|
"alltypes_static.pb.c",
|
||||||
|
"$COMMON/pb_encode_with_malloc.o",
|
||||||
|
"$COMMON/pb_decode_with_malloc.o",
|
||||||
|
"$COMMON/malloc_wrappers.o"])
|
||||||
|
|
||||||
|
|
||||||
3
tests/fuzztest/alltypes_pointer.options
Normal file
3
tests/fuzztest/alltypes_pointer.options
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Generate all fields as pointers.
|
||||||
|
* type:FT_POINTER
|
||||||
|
|
||||||
3
tests/fuzztest/alltypes_static.options
Normal file
3
tests/fuzztest/alltypes_static.options
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
* max_size:32
|
||||||
|
* max_count:8
|
||||||
|
*.extensions type:FT_IGNORE
|
||||||
189
tests/fuzztest/fuzzstub.c
Normal file
189
tests/fuzztest/fuzzstub.c
Normal file
@@ -0,0 +1,189 @@
|
|||||||
|
/* Fuzz testing for the nanopb core.
|
||||||
|
* This can be used with external fuzzers, e.g. radamsa.
|
||||||
|
* It performs most of the same checks as fuzztest, but does not feature data generation.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <pb_decode.h>
|
||||||
|
#include <pb_encode.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <assert.h>
|
||||||
|
#include <time.h>
|
||||||
|
#include <malloc_wrappers.h>
|
||||||
|
#include "alltypes_static.pb.h"
|
||||||
|
#include "alltypes_pointer.pb.h"
|
||||||
|
|
||||||
|
#define BUFSIZE 4096
|
||||||
|
|
||||||
|
static bool do_static_decode(uint8_t *buffer, size_t msglen, bool assert_success)
|
||||||
|
{
|
||||||
|
pb_istream_t stream;
|
||||||
|
bool status;
|
||||||
|
|
||||||
|
alltypes_static_AllTypes *msg = malloc_with_check(sizeof(alltypes_static_AllTypes));
|
||||||
|
stream = pb_istream_from_buffer(buffer, msglen);
|
||||||
|
status = pb_decode(&stream, alltypes_static_AllTypes_fields, msg);
|
||||||
|
|
||||||
|
if (!status && assert_success)
|
||||||
|
{
|
||||||
|
/* Anything that was successfully encoded, should be decodeable.
|
||||||
|
* One exception: strings without null terminator are encoded up
|
||||||
|
* to end of buffer, but refused on decode because the terminator
|
||||||
|
* would not fit. */
|
||||||
|
if (strcmp(stream.errmsg, "string overflow") != 0)
|
||||||
|
assert(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
free_with_check(msg);
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool do_pointer_decode(uint8_t *buffer, size_t msglen, bool assert_success)
|
||||||
|
{
|
||||||
|
pb_istream_t stream;
|
||||||
|
bool status;
|
||||||
|
alltypes_pointer_AllTypes *msg;
|
||||||
|
|
||||||
|
msg = malloc_with_check(sizeof(alltypes_pointer_AllTypes));
|
||||||
|
memset(msg, 0, sizeof(alltypes_pointer_AllTypes));
|
||||||
|
stream = pb_istream_from_buffer(buffer, msglen);
|
||||||
|
|
||||||
|
assert(get_alloc_count() == 0);
|
||||||
|
status = pb_decode(&stream, alltypes_pointer_AllTypes_fields, msg);
|
||||||
|
|
||||||
|
if (assert_success)
|
||||||
|
assert(status);
|
||||||
|
|
||||||
|
pb_release(alltypes_pointer_AllTypes_fields, msg);
|
||||||
|
assert(get_alloc_count() == 0);
|
||||||
|
|
||||||
|
free_with_check(msg);
|
||||||
|
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Do a decode -> encode -> decode -> encode roundtrip */
|
||||||
|
static void do_static_roundtrip(uint8_t *buffer, size_t msglen)
|
||||||
|
{
|
||||||
|
bool status;
|
||||||
|
uint8_t *buf2 = malloc_with_check(BUFSIZE);
|
||||||
|
uint8_t *buf3 = malloc_with_check(BUFSIZE);
|
||||||
|
size_t msglen2, msglen3;
|
||||||
|
alltypes_static_AllTypes *msg1 = malloc_with_check(sizeof(alltypes_static_AllTypes));
|
||||||
|
alltypes_static_AllTypes *msg2 = malloc_with_check(sizeof(alltypes_static_AllTypes));
|
||||||
|
memset(msg1, 0, sizeof(alltypes_static_AllTypes));
|
||||||
|
memset(msg2, 0, sizeof(alltypes_static_AllTypes));
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_istream_t stream = pb_istream_from_buffer(buffer, msglen);
|
||||||
|
status = pb_decode(&stream, alltypes_static_AllTypes_fields, msg1);
|
||||||
|
assert(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_ostream_t stream = pb_ostream_from_buffer(buf2, BUFSIZE);
|
||||||
|
status = pb_encode(&stream, alltypes_static_AllTypes_fields, msg1);
|
||||||
|
assert(status);
|
||||||
|
msglen2 = stream.bytes_written;
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_istream_t stream = pb_istream_from_buffer(buf2, msglen2);
|
||||||
|
status = pb_decode(&stream, alltypes_static_AllTypes_fields, msg2);
|
||||||
|
assert(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_ostream_t stream = pb_ostream_from_buffer(buf3, BUFSIZE);
|
||||||
|
status = pb_encode(&stream, alltypes_static_AllTypes_fields, msg2);
|
||||||
|
assert(status);
|
||||||
|
msglen3 = stream.bytes_written;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(msglen2 == msglen3);
|
||||||
|
assert(memcmp(buf2, buf3, msglen2) == 0);
|
||||||
|
|
||||||
|
free_with_check(msg1);
|
||||||
|
free_with_check(msg2);
|
||||||
|
free_with_check(buf2);
|
||||||
|
free_with_check(buf3);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Do decode -> encode -> decode -> encode roundtrip */
|
||||||
|
static void do_pointer_roundtrip(uint8_t *buffer, size_t msglen)
|
||||||
|
{
|
||||||
|
bool status;
|
||||||
|
uint8_t *buf2 = malloc_with_check(BUFSIZE);
|
||||||
|
uint8_t *buf3 = malloc_with_check(BUFSIZE);
|
||||||
|
size_t msglen2, msglen3;
|
||||||
|
alltypes_pointer_AllTypes *msg1 = malloc_with_check(sizeof(alltypes_pointer_AllTypes));
|
||||||
|
alltypes_pointer_AllTypes *msg2 = malloc_with_check(sizeof(alltypes_pointer_AllTypes));
|
||||||
|
memset(msg1, 0, sizeof(alltypes_pointer_AllTypes));
|
||||||
|
memset(msg2, 0, sizeof(alltypes_pointer_AllTypes));
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_istream_t stream = pb_istream_from_buffer(buffer, msglen);
|
||||||
|
status = pb_decode(&stream, alltypes_pointer_AllTypes_fields, msg1);
|
||||||
|
assert(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_ostream_t stream = pb_ostream_from_buffer(buf2, BUFSIZE);
|
||||||
|
status = pb_encode(&stream, alltypes_pointer_AllTypes_fields, msg1);
|
||||||
|
assert(status);
|
||||||
|
msglen2 = stream.bytes_written;
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_istream_t stream = pb_istream_from_buffer(buf2, msglen2);
|
||||||
|
status = pb_decode(&stream, alltypes_pointer_AllTypes_fields, msg2);
|
||||||
|
assert(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_ostream_t stream = pb_ostream_from_buffer(buf3, BUFSIZE);
|
||||||
|
status = pb_encode(&stream, alltypes_pointer_AllTypes_fields, msg2);
|
||||||
|
assert(status);
|
||||||
|
msglen3 = stream.bytes_written;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(msglen2 == msglen3);
|
||||||
|
assert(memcmp(buf2, buf3, msglen2) == 0);
|
||||||
|
|
||||||
|
pb_release(alltypes_pointer_AllTypes_fields, msg1);
|
||||||
|
pb_release(alltypes_pointer_AllTypes_fields, msg2);
|
||||||
|
free_with_check(msg1);
|
||||||
|
free_with_check(msg2);
|
||||||
|
free_with_check(buf2);
|
||||||
|
free_with_check(buf3);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void run_iteration()
|
||||||
|
{
|
||||||
|
uint8_t *buffer = malloc_with_check(BUFSIZE);
|
||||||
|
size_t msglen;
|
||||||
|
bool status;
|
||||||
|
|
||||||
|
msglen = fread(buffer, BUFSIZE, 1, stdin);
|
||||||
|
|
||||||
|
status = do_static_decode(buffer, msglen, false);
|
||||||
|
|
||||||
|
if (status)
|
||||||
|
do_static_roundtrip(buffer, msglen);
|
||||||
|
|
||||||
|
status = do_pointer_decode(buffer, msglen, false);
|
||||||
|
|
||||||
|
if (status)
|
||||||
|
do_pointer_roundtrip(buffer, msglen);
|
||||||
|
|
||||||
|
free_with_check(buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char **argv)
|
||||||
|
{
|
||||||
|
run_iteration();
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
431
tests/fuzztest/fuzztest.c
Normal file
431
tests/fuzztest/fuzztest.c
Normal file
@@ -0,0 +1,431 @@
|
|||||||
|
/* Fuzz testing for the nanopb core.
|
||||||
|
* Attempts to verify all the properties defined in the security model document.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <pb_decode.h>
|
||||||
|
#include <pb_encode.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <assert.h>
|
||||||
|
#include <time.h>
|
||||||
|
#include <malloc_wrappers.h>
|
||||||
|
#include "alltypes_static.pb.h"
|
||||||
|
#include "alltypes_pointer.pb.h"
|
||||||
|
|
||||||
|
static uint64_t random_seed;
|
||||||
|
|
||||||
|
/* Uses xorshift64 here instead of rand() for both speed and
|
||||||
|
* reproducibility across platforms. */
|
||||||
|
static uint32_t rand_word()
|
||||||
|
{
|
||||||
|
random_seed ^= random_seed >> 12;
|
||||||
|
random_seed ^= random_seed << 25;
|
||||||
|
random_seed ^= random_seed >> 27;
|
||||||
|
return random_seed * 2685821657736338717ULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Get a random integer in range, with approximately flat distribution. */
|
||||||
|
static int rand_int(int min, int max)
|
||||||
|
{
|
||||||
|
return rand_word() % (max + 1 - min) + min;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool rand_bool()
|
||||||
|
{
|
||||||
|
return rand_word() & 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Get a random byte, with skewed distribution.
|
||||||
|
* Important corner cases like 0xFF, 0x00 and 0xFE occur more
|
||||||
|
* often than other values. */
|
||||||
|
static uint8_t rand_byte()
|
||||||
|
{
|
||||||
|
uint32_t w = rand_word();
|
||||||
|
uint8_t b = w & 0xFF;
|
||||||
|
if (w & 0x100000)
|
||||||
|
b >>= (w >> 8) & 7;
|
||||||
|
if (w & 0x200000)
|
||||||
|
b <<= (w >> 12) & 7;
|
||||||
|
if (w & 0x400000)
|
||||||
|
b ^= 0xFF;
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Get a random length, with skewed distribution.
|
||||||
|
* Favors the shorter lengths, but always atleast 1. */
|
||||||
|
static size_t rand_len(size_t max)
|
||||||
|
{
|
||||||
|
uint32_t w = rand_word();
|
||||||
|
size_t s;
|
||||||
|
if (w & 0x800000)
|
||||||
|
w &= 3;
|
||||||
|
else if (w & 0x400000)
|
||||||
|
w &= 15;
|
||||||
|
else if (w & 0x200000)
|
||||||
|
w &= 255;
|
||||||
|
|
||||||
|
s = (w % max);
|
||||||
|
if (s == 0)
|
||||||
|
s = 1;
|
||||||
|
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fills a buffer with random data with skewed distribution. */
|
||||||
|
static void rand_fill(uint8_t *buf, size_t count)
|
||||||
|
{
|
||||||
|
while (count--)
|
||||||
|
*buf++ = rand_byte();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fill with random protobuf-like data */
|
||||||
|
static size_t rand_fill_protobuf(uint8_t *buf, size_t min_bytes, size_t max_bytes, int min_tag)
|
||||||
|
{
|
||||||
|
pb_ostream_t stream = pb_ostream_from_buffer(buf, max_bytes);
|
||||||
|
|
||||||
|
while(stream.bytes_written < min_bytes)
|
||||||
|
{
|
||||||
|
pb_wire_type_t wt = rand_int(0, 3);
|
||||||
|
if (wt == 3) wt = 5; /* Gap in values */
|
||||||
|
|
||||||
|
if (!pb_encode_tag(&stream, wt, rand_int(min_tag, min_tag + 512)))
|
||||||
|
break;
|
||||||
|
|
||||||
|
if (wt == PB_WT_VARINT)
|
||||||
|
{
|
||||||
|
uint64_t value;
|
||||||
|
rand_fill((uint8_t*)&value, sizeof(value));
|
||||||
|
pb_encode_varint(&stream, value);
|
||||||
|
}
|
||||||
|
else if (wt == PB_WT_64BIT)
|
||||||
|
{
|
||||||
|
uint64_t value;
|
||||||
|
rand_fill((uint8_t*)&value, sizeof(value));
|
||||||
|
pb_encode_fixed64(&stream, &value);
|
||||||
|
}
|
||||||
|
else if (wt == PB_WT_32BIT)
|
||||||
|
{
|
||||||
|
uint32_t value;
|
||||||
|
rand_fill((uint8_t*)&value, sizeof(value));
|
||||||
|
pb_encode_fixed32(&stream, &value);
|
||||||
|
}
|
||||||
|
else if (wt == PB_WT_STRING)
|
||||||
|
{
|
||||||
|
size_t len;
|
||||||
|
uint8_t *buf;
|
||||||
|
|
||||||
|
if (min_bytes > stream.bytes_written)
|
||||||
|
len = rand_len(min_bytes - stream.bytes_written);
|
||||||
|
else
|
||||||
|
len = 0;
|
||||||
|
|
||||||
|
buf = malloc(len);
|
||||||
|
pb_encode_varint(&stream, len);
|
||||||
|
rand_fill(buf, len);
|
||||||
|
pb_write(&stream, buf, len);
|
||||||
|
free(buf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return stream.bytes_written;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Given a buffer of data, mess it up a bit */
|
||||||
|
static void rand_mess(uint8_t *buf, size_t count)
|
||||||
|
{
|
||||||
|
int m = rand_int(0, 3);
|
||||||
|
|
||||||
|
if (m == 0)
|
||||||
|
{
|
||||||
|
/* Replace random substring */
|
||||||
|
int s = rand_int(0, count - 1);
|
||||||
|
int l = rand_len(count - s);
|
||||||
|
rand_fill(buf + s, l);
|
||||||
|
}
|
||||||
|
else if (m == 1)
|
||||||
|
{
|
||||||
|
/* Swap random bytes */
|
||||||
|
int a = rand_int(0, count - 1);
|
||||||
|
int b = rand_int(0, count - 1);
|
||||||
|
int x = buf[a];
|
||||||
|
buf[a] = buf[b];
|
||||||
|
buf[b] = x;
|
||||||
|
}
|
||||||
|
else if (m == 2)
|
||||||
|
{
|
||||||
|
/* Duplicate substring */
|
||||||
|
int s = rand_int(0, count - 2);
|
||||||
|
int l = rand_len((count - s) / 2);
|
||||||
|
memcpy(buf + s + l, buf + s, l);
|
||||||
|
}
|
||||||
|
else if (m == 3)
|
||||||
|
{
|
||||||
|
/* Add random protobuf noise */
|
||||||
|
int s = rand_int(0, count - 1);
|
||||||
|
int l = rand_len(count - s);
|
||||||
|
rand_fill_protobuf(buf + s, l, count - s, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Some default data to put in the message */
|
||||||
|
static const alltypes_static_AllTypes initval = alltypes_static_AllTypes_init_default;
|
||||||
|
|
||||||
|
#define BUFSIZE 4096
|
||||||
|
|
||||||
|
static bool do_static_encode(uint8_t *buffer, size_t *msglen)
|
||||||
|
{
|
||||||
|
pb_ostream_t stream;
|
||||||
|
bool status;
|
||||||
|
|
||||||
|
/* Allocate a message and fill it with defaults */
|
||||||
|
alltypes_static_AllTypes *msg = malloc_with_check(sizeof(alltypes_static_AllTypes));
|
||||||
|
memcpy(msg, &initval, sizeof(initval));
|
||||||
|
|
||||||
|
/* Apply randomness to the data before encoding */
|
||||||
|
while (rand_int(0, 7))
|
||||||
|
rand_mess((uint8_t*)msg, sizeof(alltypes_static_AllTypes));
|
||||||
|
|
||||||
|
stream = pb_ostream_from_buffer(buffer, BUFSIZE);
|
||||||
|
status = pb_encode(&stream, alltypes_static_AllTypes_fields, msg);
|
||||||
|
assert(stream.bytes_written <= BUFSIZE);
|
||||||
|
assert(stream.bytes_written <= alltypes_static_AllTypes_size);
|
||||||
|
|
||||||
|
*msglen = stream.bytes_written;
|
||||||
|
free_with_check(msg);
|
||||||
|
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Append or prepend protobuf noise */
|
||||||
|
static void do_protobuf_noise(uint8_t *buffer, size_t *msglen)
|
||||||
|
{
|
||||||
|
int m = rand_int(0, 2);
|
||||||
|
size_t max_size = BUFSIZE - 32 - *msglen;
|
||||||
|
if (m == 1)
|
||||||
|
{
|
||||||
|
/* Prepend */
|
||||||
|
uint8_t *tmp = malloc_with_check(BUFSIZE);
|
||||||
|
size_t s = rand_fill_protobuf(tmp, rand_len(max_size), BUFSIZE - *msglen, 512);
|
||||||
|
memmove(buffer + s, buffer, *msglen);
|
||||||
|
memcpy(buffer, tmp, s);
|
||||||
|
free_with_check(tmp);
|
||||||
|
*msglen += s;
|
||||||
|
}
|
||||||
|
else if (m == 2)
|
||||||
|
{
|
||||||
|
/* Append */
|
||||||
|
size_t s = rand_fill_protobuf(buffer + *msglen, rand_len(max_size), BUFSIZE - *msglen, 512);
|
||||||
|
*msglen += s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool do_static_decode(uint8_t *buffer, size_t msglen, bool assert_success)
|
||||||
|
{
|
||||||
|
pb_istream_t stream;
|
||||||
|
bool status;
|
||||||
|
|
||||||
|
alltypes_static_AllTypes *msg = malloc_with_check(sizeof(alltypes_static_AllTypes));
|
||||||
|
rand_fill((uint8_t*)msg, sizeof(alltypes_static_AllTypes));
|
||||||
|
stream = pb_istream_from_buffer(buffer, msglen);
|
||||||
|
status = pb_decode(&stream, alltypes_static_AllTypes_fields, msg);
|
||||||
|
|
||||||
|
if (!status && assert_success)
|
||||||
|
{
|
||||||
|
/* Anything that was successfully encoded, should be decodeable.
|
||||||
|
* One exception: strings without null terminator are encoded up
|
||||||
|
* to end of buffer, but refused on decode because the terminator
|
||||||
|
* would not fit. */
|
||||||
|
if (strcmp(stream.errmsg, "string overflow") != 0)
|
||||||
|
assert(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
free_with_check(msg);
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool do_pointer_decode(uint8_t *buffer, size_t msglen, bool assert_success)
|
||||||
|
{
|
||||||
|
pb_istream_t stream;
|
||||||
|
bool status;
|
||||||
|
alltypes_pointer_AllTypes *msg;
|
||||||
|
|
||||||
|
msg = malloc_with_check(sizeof(alltypes_pointer_AllTypes));
|
||||||
|
memset(msg, 0, sizeof(alltypes_pointer_AllTypes));
|
||||||
|
stream = pb_istream_from_buffer(buffer, msglen);
|
||||||
|
|
||||||
|
assert(get_alloc_count() == 0);
|
||||||
|
status = pb_decode(&stream, alltypes_pointer_AllTypes_fields, msg);
|
||||||
|
|
||||||
|
if (assert_success)
|
||||||
|
assert(status);
|
||||||
|
|
||||||
|
pb_release(alltypes_pointer_AllTypes_fields, msg);
|
||||||
|
assert(get_alloc_count() == 0);
|
||||||
|
|
||||||
|
free_with_check(msg);
|
||||||
|
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Do a decode -> encode -> decode -> encode roundtrip */
|
||||||
|
static void do_static_roundtrip(uint8_t *buffer, size_t msglen)
|
||||||
|
{
|
||||||
|
bool status;
|
||||||
|
uint8_t *buf2 = malloc_with_check(BUFSIZE);
|
||||||
|
uint8_t *buf3 = malloc_with_check(BUFSIZE);
|
||||||
|
size_t msglen2, msglen3;
|
||||||
|
alltypes_static_AllTypes *msg1 = malloc_with_check(sizeof(alltypes_static_AllTypes));
|
||||||
|
alltypes_static_AllTypes *msg2 = malloc_with_check(sizeof(alltypes_static_AllTypes));
|
||||||
|
memset(msg1, 0, sizeof(alltypes_static_AllTypes));
|
||||||
|
memset(msg2, 0, sizeof(alltypes_static_AllTypes));
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_istream_t stream = pb_istream_from_buffer(buffer, msglen);
|
||||||
|
status = pb_decode(&stream, alltypes_static_AllTypes_fields, msg1);
|
||||||
|
assert(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_ostream_t stream = pb_ostream_from_buffer(buf2, BUFSIZE);
|
||||||
|
status = pb_encode(&stream, alltypes_static_AllTypes_fields, msg1);
|
||||||
|
assert(status);
|
||||||
|
msglen2 = stream.bytes_written;
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_istream_t stream = pb_istream_from_buffer(buf2, msglen2);
|
||||||
|
status = pb_decode(&stream, alltypes_static_AllTypes_fields, msg2);
|
||||||
|
assert(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_ostream_t stream = pb_ostream_from_buffer(buf3, BUFSIZE);
|
||||||
|
status = pb_encode(&stream, alltypes_static_AllTypes_fields, msg2);
|
||||||
|
assert(status);
|
||||||
|
msglen3 = stream.bytes_written;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(msglen2 == msglen3);
|
||||||
|
assert(memcmp(buf2, buf3, msglen2) == 0);
|
||||||
|
|
||||||
|
free_with_check(msg1);
|
||||||
|
free_with_check(msg2);
|
||||||
|
free_with_check(buf2);
|
||||||
|
free_with_check(buf3);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Do decode -> encode -> decode -> encode roundtrip */
|
||||||
|
static void do_pointer_roundtrip(uint8_t *buffer, size_t msglen)
|
||||||
|
{
|
||||||
|
bool status;
|
||||||
|
uint8_t *buf2 = malloc_with_check(BUFSIZE);
|
||||||
|
uint8_t *buf3 = malloc_with_check(BUFSIZE);
|
||||||
|
size_t msglen2, msglen3;
|
||||||
|
alltypes_pointer_AllTypes *msg1 = malloc_with_check(sizeof(alltypes_pointer_AllTypes));
|
||||||
|
alltypes_pointer_AllTypes *msg2 = malloc_with_check(sizeof(alltypes_pointer_AllTypes));
|
||||||
|
memset(msg1, 0, sizeof(alltypes_pointer_AllTypes));
|
||||||
|
memset(msg2, 0, sizeof(alltypes_pointer_AllTypes));
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_istream_t stream = pb_istream_from_buffer(buffer, msglen);
|
||||||
|
status = pb_decode(&stream, alltypes_pointer_AllTypes_fields, msg1);
|
||||||
|
assert(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_ostream_t stream = pb_ostream_from_buffer(buf2, BUFSIZE);
|
||||||
|
status = pb_encode(&stream, alltypes_pointer_AllTypes_fields, msg1);
|
||||||
|
assert(status);
|
||||||
|
msglen2 = stream.bytes_written;
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_istream_t stream = pb_istream_from_buffer(buf2, msglen2);
|
||||||
|
status = pb_decode(&stream, alltypes_pointer_AllTypes_fields, msg2);
|
||||||
|
assert(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
pb_ostream_t stream = pb_ostream_from_buffer(buf3, BUFSIZE);
|
||||||
|
status = pb_encode(&stream, alltypes_pointer_AllTypes_fields, msg2);
|
||||||
|
assert(status);
|
||||||
|
msglen3 = stream.bytes_written;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(msglen2 == msglen3);
|
||||||
|
assert(memcmp(buf2, buf3, msglen2) == 0);
|
||||||
|
|
||||||
|
pb_release(alltypes_pointer_AllTypes_fields, msg1);
|
||||||
|
pb_release(alltypes_pointer_AllTypes_fields, msg2);
|
||||||
|
free_with_check(msg1);
|
||||||
|
free_with_check(msg2);
|
||||||
|
free_with_check(buf2);
|
||||||
|
free_with_check(buf3);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void run_iteration()
|
||||||
|
{
|
||||||
|
uint8_t *buffer = malloc_with_check(BUFSIZE);
|
||||||
|
size_t msglen;
|
||||||
|
bool status;
|
||||||
|
|
||||||
|
rand_fill(buffer, BUFSIZE);
|
||||||
|
|
||||||
|
if (do_static_encode(buffer, &msglen))
|
||||||
|
{
|
||||||
|
do_protobuf_noise(buffer, &msglen);
|
||||||
|
|
||||||
|
status = do_static_decode(buffer, msglen, true);
|
||||||
|
|
||||||
|
if (status)
|
||||||
|
do_static_roundtrip(buffer, msglen);
|
||||||
|
|
||||||
|
status = do_pointer_decode(buffer, msglen, true);
|
||||||
|
|
||||||
|
if (status)
|
||||||
|
do_pointer_roundtrip(buffer, msglen);
|
||||||
|
|
||||||
|
/* Apply randomness to the encoded data */
|
||||||
|
while (rand_bool())
|
||||||
|
rand_mess(buffer, BUFSIZE);
|
||||||
|
|
||||||
|
/* Apply randomness to encoded data length */
|
||||||
|
if (rand_bool())
|
||||||
|
msglen = rand_int(0, BUFSIZE);
|
||||||
|
|
||||||
|
status = do_static_decode(buffer, msglen, false);
|
||||||
|
do_pointer_decode(buffer, msglen, status);
|
||||||
|
|
||||||
|
if (status)
|
||||||
|
{
|
||||||
|
do_static_roundtrip(buffer, msglen);
|
||||||
|
do_pointer_roundtrip(buffer, msglen);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
free_with_check(buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char **argv)
|
||||||
|
{
|
||||||
|
int i;
|
||||||
|
if (argc > 1)
|
||||||
|
{
|
||||||
|
random_seed = atol(argv[1]);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
random_seed = time(NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
fprintf(stderr, "Random seed: %llu\n", (long long unsigned)random_seed);
|
||||||
|
|
||||||
|
for (i = 0; i < 10000; i++)
|
||||||
|
{
|
||||||
|
run_iteration();
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
12
tests/fuzztest/run_radamsa.sh
Executable file
12
tests/fuzztest/run_radamsa.sh
Executable file
@@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
TMP=`tempfile`
|
||||||
|
|
||||||
|
echo $TMP
|
||||||
|
while true
|
||||||
|
do
|
||||||
|
radamsa sample_data/* > $TMP
|
||||||
|
$1 < $TMP
|
||||||
|
test $? -gt 127 && break
|
||||||
|
done
|
||||||
|
|
||||||
BIN
tests/fuzztest/sample_data/sample1.pb
Normal file
BIN
tests/fuzztest/sample_data/sample1.pb
Normal file
Binary file not shown.
BIN
tests/fuzztest/sample_data/sample2.pb
Normal file
BIN
tests/fuzztest/sample_data/sample2.pb
Normal file
Binary file not shown.
12
tests/mem_release/SConscript
Normal file
12
tests/mem_release/SConscript
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
Import("env", "malloc_env")
|
||||||
|
|
||||||
|
env.NanopbProto("mem_release.proto")
|
||||||
|
|
||||||
|
test = malloc_env.Program(["mem_release.c",
|
||||||
|
"mem_release.pb.c",
|
||||||
|
"$COMMON/pb_encode_with_malloc.o",
|
||||||
|
"$COMMON/pb_decode_with_malloc.o",
|
||||||
|
"$COMMON/malloc_wrappers.o"])
|
||||||
|
|
||||||
|
env.RunTest(test)
|
||||||
|
|
||||||
106
tests/mem_release/mem_release.c
Normal file
106
tests/mem_release/mem_release.c
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
/* Make sure that all fields are freed in various scenarios. */
|
||||||
|
|
||||||
|
#include <pb_decode.h>
|
||||||
|
#include <pb_encode.h>
|
||||||
|
#include <malloc_wrappers.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <test_helpers.h>
|
||||||
|
#include "mem_release.pb.h"
|
||||||
|
|
||||||
|
#define TEST(x) if (!(x)) { \
|
||||||
|
fprintf(stderr, "Test " #x " on line %d failed.\n", __LINE__); \
|
||||||
|
return false; \
|
||||||
|
}
|
||||||
|
|
||||||
|
static char *test_str_arr[] = {"1", "2", ""};
|
||||||
|
static SubMessage test_msg_arr[] = {SubMessage_init_zero, SubMessage_init_zero};
|
||||||
|
|
||||||
|
static bool do_test()
|
||||||
|
{
|
||||||
|
uint8_t buffer[256];
|
||||||
|
size_t msgsize;
|
||||||
|
|
||||||
|
/* Construct a message with various fields filled in */
|
||||||
|
{
|
||||||
|
TestMessage msg = TestMessage_init_zero;
|
||||||
|
pb_extension_t ext2;
|
||||||
|
pb_ostream_t stream;
|
||||||
|
msg.static_req_submsg.dynamic_str = "12345";
|
||||||
|
msg.static_req_submsg.dynamic_str_arr_count = 3;
|
||||||
|
msg.static_req_submsg.dynamic_str_arr = test_str_arr;
|
||||||
|
msg.static_req_submsg.dynamic_submsg_count = 2;
|
||||||
|
msg.static_req_submsg.dynamic_submsg = test_msg_arr;
|
||||||
|
msg.static_req_submsg.dynamic_submsg[1].dynamic_str = "abc";
|
||||||
|
msg.static_opt_submsg.dynamic_str = "abc";
|
||||||
|
msg.has_static_opt_submsg = true;
|
||||||
|
msg.dynamic_submsg = &msg.static_req_submsg;
|
||||||
|
|
||||||
|
msg.extensions = &ext2;
|
||||||
|
ext2.type = &static_ext;
|
||||||
|
ext2.dest = &msg.static_req_submsg;
|
||||||
|
ext2.next = NULL;
|
||||||
|
|
||||||
|
stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
|
||||||
|
if (!pb_encode(&stream, TestMessage_fields, &msg))
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Encode failed: %s\n", PB_GET_ERROR(&stream));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
msgsize = stream.bytes_written;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Output encoded message for debug */
|
||||||
|
SET_BINARY_MODE(stdout);
|
||||||
|
fwrite(buffer, 1, msgsize, stdout);
|
||||||
|
|
||||||
|
/* Decode memory using dynamic allocation */
|
||||||
|
{
|
||||||
|
TestMessage msg = TestMessage_init_zero;
|
||||||
|
pb_istream_t stream;
|
||||||
|
SubMessage ext2_dest = SubMessage_init_zero;
|
||||||
|
pb_extension_t ext2;
|
||||||
|
|
||||||
|
msg.extensions = &ext2;
|
||||||
|
ext2.type = &static_ext;
|
||||||
|
ext2.dest = &ext2_dest;
|
||||||
|
ext2.next = NULL;
|
||||||
|
|
||||||
|
stream = pb_istream_from_buffer(buffer, msgsize);
|
||||||
|
if (!pb_decode(&stream, TestMessage_fields, &msg))
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Decode failed: %s\n", PB_GET_ERROR(&stream));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Make sure it encodes back to same data */
|
||||||
|
{
|
||||||
|
uint8_t buffer2[256];
|
||||||
|
pb_ostream_t ostream = pb_ostream_from_buffer(buffer2, sizeof(buffer2));
|
||||||
|
TEST(pb_encode(&ostream, TestMessage_fields, &msg));
|
||||||
|
TEST(ostream.bytes_written == msgsize);
|
||||||
|
TEST(memcmp(buffer, buffer2, msgsize) == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Make sure that malloc counters work */
|
||||||
|
TEST(get_alloc_count() > 0);
|
||||||
|
|
||||||
|
/* Make sure that pb_release releases everything */
|
||||||
|
pb_release(TestMessage_fields, &msg);
|
||||||
|
TEST(get_alloc_count() == 0);
|
||||||
|
|
||||||
|
/* Check that double-free is a no-op */
|
||||||
|
pb_release(TestMessage_fields, &msg);
|
||||||
|
TEST(get_alloc_count() == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
if (do_test())
|
||||||
|
return 0;
|
||||||
|
else
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
23
tests/mem_release/mem_release.proto
Normal file
23
tests/mem_release/mem_release.proto
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
syntax = "proto2";
|
||||||
|
import "nanopb.proto";
|
||||||
|
|
||||||
|
message SubMessage
|
||||||
|
{
|
||||||
|
optional string dynamic_str = 1 [(nanopb).type = FT_POINTER];
|
||||||
|
repeated string dynamic_str_arr = 2 [(nanopb).type = FT_POINTER];
|
||||||
|
repeated SubMessage dynamic_submsg = 3 [(nanopb).type = FT_POINTER];
|
||||||
|
}
|
||||||
|
|
||||||
|
message TestMessage
|
||||||
|
{
|
||||||
|
required SubMessage static_req_submsg = 1 [(nanopb).type = FT_STATIC];
|
||||||
|
optional SubMessage dynamic_submsg = 2 [(nanopb).type = FT_POINTER];
|
||||||
|
optional SubMessage static_opt_submsg = 3 [(nanopb).type = FT_STATIC];
|
||||||
|
extensions 100 to 200;
|
||||||
|
}
|
||||||
|
|
||||||
|
extend TestMessage
|
||||||
|
{
|
||||||
|
optional SubMessage static_ext = 101 [(nanopb).type = FT_STATIC];
|
||||||
|
}
|
||||||
|
|
||||||
@@ -5,3 +5,6 @@ pb_callback_t int32_callback;
|
|||||||
\sEnumValue1 = 1
|
\sEnumValue1 = 1
|
||||||
Message5_EnumValue1
|
Message5_EnumValue1
|
||||||
} pb_packed my_packed_struct;
|
} pb_packed my_packed_struct;
|
||||||
|
! skipped_field
|
||||||
|
! SkippedMessage
|
||||||
|
|
||||||
|
|||||||
@@ -63,11 +63,15 @@ message my_packed_struct
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Message with ignored field
|
// Message with ignored field
|
||||||
// Note: doesn't really test if the field is missing in the output,
|
|
||||||
// but atleast tests that the output compiles.
|
|
||||||
message Message6
|
message Message6
|
||||||
{
|
{
|
||||||
required int32 field1 = 1;
|
required int32 field1 = 1;
|
||||||
optional int32 field2 = 2 [(nanopb).type = FT_IGNORE];
|
optional int32 skipped_field = 2 [(nanopb).type = FT_IGNORE];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Message that is skipped
|
||||||
|
message SkippedMessage
|
||||||
|
{
|
||||||
|
option (nanopb_msgopt).skip_message = true;
|
||||||
|
required int32 foo = 1;
|
||||||
|
}
|
||||||
|
|||||||
9
tests/regression/issue_125/SConscript
Normal file
9
tests/regression/issue_125/SConscript
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
# Regression test for Issue 125: Wrong identifier name for extension fields
|
||||||
|
|
||||||
|
Import("env")
|
||||||
|
|
||||||
|
env.NanopbProto(["extensionbug", "extensionbug.options"])
|
||||||
|
env.Object('extensionbug.pb.c')
|
||||||
|
|
||||||
|
env.Match(['extensionbug.pb.h', 'extensionbug.expected'])
|
||||||
|
|
||||||
3
tests/regression/issue_125/extensionbug.expected
Normal file
3
tests/regression/issue_125/extensionbug.expected
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
pb_extension_type_t Message2_extras
|
||||||
|
uint32_t field2
|
||||||
|
|
||||||
4
tests/regression/issue_125/extensionbug.options
Normal file
4
tests/regression/issue_125/extensionbug.options
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
* type:FT_IGNORE
|
||||||
|
|
||||||
|
Message2.extras type:FT_STATIC
|
||||||
|
Message2.field2 type:FT_STATIC
|
||||||
16
tests/regression/issue_125/extensionbug.proto
Normal file
16
tests/regression/issue_125/extensionbug.proto
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
message Message1
|
||||||
|
{
|
||||||
|
optional uint32 fieldA = 1;
|
||||||
|
extensions 30 to max;
|
||||||
|
}
|
||||||
|
|
||||||
|
message Message2
|
||||||
|
{
|
||||||
|
extend Message1
|
||||||
|
{
|
||||||
|
optional Message2 extras = 30;
|
||||||
|
}
|
||||||
|
|
||||||
|
optional uint32 field1 = 1;
|
||||||
|
optional uint32 field2 = 2;
|
||||||
|
}
|
||||||
@@ -85,9 +85,20 @@ def add_nanopb_builders(env):
|
|||||||
data = open(str(source[0]), 'rU').read()
|
data = open(str(source[0]), 'rU').read()
|
||||||
patterns = open(str(source[1]))
|
patterns = open(str(source[1]))
|
||||||
for pattern in patterns:
|
for pattern in patterns:
|
||||||
if pattern.strip() and not re.search(pattern.strip(), data, re.MULTILINE):
|
if pattern.strip():
|
||||||
print '\033[31m[FAIL]\033[0m Pattern not found in ' + str(source[0]) + ': ' + pattern
|
invert = False
|
||||||
return 1
|
if pattern.startswith('! '):
|
||||||
|
invert = True
|
||||||
|
pattern = pattern[2:]
|
||||||
|
|
||||||
|
status = re.search(pattern.strip(), data, re.MULTILINE)
|
||||||
|
|
||||||
|
if not status and not invert:
|
||||||
|
print '\033[31m[FAIL]\033[0m Pattern not found in ' + str(source[0]) + ': ' + pattern
|
||||||
|
return 1
|
||||||
|
elif status and invert:
|
||||||
|
print '\033[31m[FAIL]\033[0m Pattern should not exist, but does in ' + str(source[0]) + ': ' + pattern
|
||||||
|
return 1
|
||||||
else:
|
else:
|
||||||
print '\033[32m[ OK ]\033[0m All patterns found in ' + str(source[0])
|
print '\033[32m[ OK ]\033[0m All patterns found in ' + str(source[0])
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
Reference in New Issue
Block a user