1
1
mirror of https://github.com/swaywm/sway synced 2025-03-03 18:11:22 +01:00
sway/common/readline.c
Dan Robertson aa15629f17
Fix memory errors
- read_line: OOB write when a line in /proc/modules contains a
   terminating character at size position.
 - handle_view_created: Ensure that the list_t returned by criteria_for
   is free'd after use
 - ipc_event_binding_keyboard/ipc_event_binding: Properly handle
   json_object reference counting and ownership.
2018-02-11 04:57:54 +00:00

75 lines
1.4 KiB
C

#include "readline.h"
#include "log.h"
#include <stdlib.h>
#include <stdio.h>
char *read_line(FILE *file) {
size_t length = 0, size = 128;
char *string = malloc(size);
char lastChar = '\0';
if (!string) {
sway_log(L_ERROR, "Unable to allocate memory for read_line");
return NULL;
}
while (1) {
int c = getc(file);
if (c == '\n' && lastChar == '\\'){
--length; // Ignore last character.
lastChar = '\0';
continue;
}
if (c == EOF || c == '\n' || c == '\0') {
break;
}
if (c == '\r') {
continue;
}
lastChar = c;
if (length == size) {
char *new_string = realloc(string, size *= 2);
if (!new_string) {
free(string);
sway_log(L_ERROR, "Unable to allocate memory for read_line");
return NULL;
}
string = new_string;
}
string[length++] = c;
}
if (length + 1 >= size) {
char *new_string = realloc(string, length + 1);
if (!new_string) {
free(string);
return NULL;
}
string = new_string;
}
string[length] = '\0';
return string;
}
char *read_line_buffer(FILE *file, char *string, size_t string_len) {
size_t length = 0;
if (!string) {
return NULL;
}
while (1) {
int c = getc(file);
if (c == EOF || c == '\n' || c == '\0') {
break;
}
if (c == '\r') {
continue;
}
string[length++] = c;
if (string_len <= length) {
return NULL;
}
}
if (length + 1 == string_len) {
return NULL;
}
string[length] = '\0';
return string;
}