@@ -132,6 +132,9 @@ static PyObject* py_count_kmers_from_sequence(PyObject* self, PyObject* args) {
132
132
struct AwFmKmerSearchList * searchList =
133
133
awFmCreateKmerSearchList (numKmers );
134
134
135
+ // Error value for erroneous size_t conversions from negative python longs
136
+ const size_t ERROR_VALUE = (size_t )-1 ;
137
+
135
138
// Fill the search list with the kmers
136
139
searchList -> count = numKmers ;
137
140
for (size_t i = 0 ; i < numKmers ; i ++ ) {
@@ -147,11 +150,28 @@ static PyObject* py_count_kmers_from_sequence(PyObject* self, PyObject* args) {
147
150
return NULL ;
148
151
}
149
152
153
+ // NB: Throws an OverflowError if negative when converting to size_t
154
+ // and returns a (size_t)-1 value. Note size_t is unsigned.
150
155
size_t kmer_index = PyLong_AsSize_t (indexObj );
156
+ if (kmer_index == ERROR_VALUE &&
157
+ PyErr_Occurred ()) {
158
+ PyErr_Clear ();
159
+ PyErr_SetString (PyExc_IndexError , "All elements of the the index "
160
+ "list must be non-negative integers" );
161
+ return NULL ;
162
+ }
163
+
151
164
size_t kmer_length = PyLong_AsSize_t (lengthObj );
165
+ if (kmer_index == ERROR_VALUE &&
166
+ PyErr_Occurred ()) {
167
+ PyErr_Clear ();
168
+ PyErr_SetString (PyExc_ValueError , "All lengths in the length list"
169
+ "list must be non-negative integers" );
170
+ return NULL ;
171
+ }
152
172
153
173
// TODO: Assert or check that the index + length does not go out of
154
- // bounds
174
+ // bounds to protect against nonsense input and segmentation faults
155
175
searchList -> kmerSearchData [i ].kmerLength = kmer_length ;
156
176
searchList -> kmerSearchData [i ].kmerString =
157
177
& inputByteSequence [kmer_index ];
0 commit comments