Skip to content

Commit 23342c0

Browse files
committed
stmhal: Bug fix for usocket's accept and setsockopt methods.
accept might raise an exception, in which case the new socket is not fully created. It has a finaliser so will run close() method when GC'd. Before this patch close would try to close an invalid socket. Now fixed. setsockopt took address of stack value which became out of scope. Now fixed.
1 parent 91232d3 commit 23342c0

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

stmhal/modusocket.c

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,10 +132,11 @@ STATIC mp_obj_t socket_accept(mp_obj_t self_in) {
132132
mod_network_socket_obj_t *self = self_in;
133133

134134
// create new socket object
135+
// starts with empty NIC so that finaliser doesn't run close() method if accept() fails
135136
mod_network_socket_obj_t *socket2 = m_new_obj_with_finaliser(mod_network_socket_obj_t);
136137
socket2->base.type = (mp_obj_t)&socket_type;
137-
socket2->nic = self->nic;
138-
socket2->nic_type = self->nic_type;
138+
socket2->nic = MP_OBJ_NULL;
139+
socket2->nic_type = NULL;
139140

140141
// accept incoming connection
141142
uint8_t ip[MOD_NETWORK_IPADDR_BUF_SIZE];
@@ -145,6 +146,10 @@ STATIC mp_obj_t socket_accept(mp_obj_t self_in) {
145146
nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(_errno)));
146147
}
147148

149+
// new socket has valid state, so set the NIC to the same as parent
150+
socket2->nic = self->nic;
151+
socket2->nic_type = self->nic_type;
152+
148153
// make the return value
149154
mp_obj_tuple_t *client = mp_obj_new_tuple(2, NULL);
150155
client->items[0] = socket2;
@@ -281,8 +286,9 @@ STATIC mp_obj_t socket_setsockopt(mp_uint_t n_args, const mp_obj_t *args) {
281286

282287
const void *optval;
283288
mp_uint_t optlen;
289+
mp_int_t val;
284290
if (mp_obj_is_integer(args[3])) {
285-
mp_int_t val = mp_obj_int_get_truncated(args[3]);
291+
val = mp_obj_int_get_truncated(args[3]);
286292
optval = &val;
287293
optlen = sizeof(val);
288294
} else {

0 commit comments

Comments
 (0)