Skip to content

Commit

Permalink
Fix mqtt5 code using wrong letter to pass int types (#417)
Browse files Browse the repository at this point in the history
**Issue:**
Mysterious crashes due to using the wrong letter when passing variables between C and Python.

**Background:**
Python's c-api uses [misc letters](https://docs.python.org/3/c-api/arg.html) to indicate various integer types. This way of passing args slips through C's type-checking mechanisms and it's easy to get things wrong, the compiler won't warn you.

Also, the Python docs refer to old-school C type names like `unsigned short`. Our AWS C code usually uses the less-confusing fixed-width sizes like `uint16_t`. But it gets confusing when you need to cross-reference against the python docs.

**Description of changes:**
- Fix (hopefully) everywhere we got an int type wrong
- Cast integers to the type we expect, so the compiler warns us if we accidentally have a "narrowing" error
- Move the type comments to the start of line, instead of end, so they're easier to read
  • Loading branch information
graebm authored Dec 6, 2022
1 parent 86f4640 commit fbe10df
Show file tree
Hide file tree
Showing 3 changed files with 241 additions and 230 deletions.
2 changes: 1 addition & 1 deletion awscrt/mqtt5.py
Original file line number Diff line number Diff line change
Expand Up @@ -1399,7 +1399,7 @@ def _on_publish(
publish_packet.retain = retain

if payload_format_indicator_exists:
publish_packet.payload_format_indicator = payload_format_indicator
publish_packet.payload_format_indicator = PayloadFormatIndicator(payload_format_indicator)
if message_expiry_interval_sec_exists:
publish_packet.message_expiry_interval_sec = message_expiry_interval_sec
if topic_alias_exists:
Expand Down
11 changes: 11 additions & 0 deletions source/module.c
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,17 @@

#include <memoryobject.h>

/* Sanity check that the fixed-size types AWS C code tends to use
* align with the the vanilla C types Python tends to use.
* This is important when passing arguments between C and Python
* via things like PyArg_ParseTuple() and PyObject_CallFunction()
* https://docs.python.org/3/c-api/arg.html */
AWS_STATIC_ASSERT(sizeof(uint8_t) == sizeof(unsigned char)); /* we pass uint8_t as "B" (unsigned char) */
AWS_STATIC_ASSERT(sizeof(uint16_t) == sizeof(unsigned short)); /* we pass uint16_t as "H" (unsigned short) */
AWS_STATIC_ASSERT(sizeof(uint32_t) == sizeof(unsigned int)); /* we pass uint32_t as "I" (unsigned int) */
AWS_STATIC_ASSERT(sizeof(uint64_t) == sizeof(unsigned long long)); /* we pass uint64_t as "K" (unsigned long long) */
AWS_STATIC_ASSERT(sizeof(enum aws_log_level) == sizeof(int)); /* we pass enums as "i" (int) */

static struct aws_logger s_logger;
static bool s_logger_init = false;

Expand Down
Loading

0 comments on commit fbe10df

Please sign in to comment.