]> sigrok.org Git - libserialport.git/blame - serialport.c
Port name string length now no longer needs to be passed around.
[libserialport.git] / serialport.c
CommitLineData
74510d4b
ML
1/*
2 * This file is part of the libserialport project.
3 *
4 * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5 * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
6 * Copyright (C) 2013 Martin Ling <martin-libserialport@earth.li>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Lesser General Public License as
10 * published by the Free Software Foundation, either version 3 of the
11 * License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#include <string.h>
23#include <sys/types.h>
24#include <sys/stat.h>
25#include <fcntl.h>
26#include <unistd.h>
3b63f34d
ML
27#include <stdlib.h>
28#include <errno.h>
74510d4b
ML
29#ifdef _WIN32
30#include <windows.h>
3b63f34d 31#include <tchar.h>
74510d4b 32#else
74510d4b
ML
33#include <termios.h>
34#include <sys/ioctl.h>
35#endif
3b63f34d 36#ifdef __APPLE__
1ebf4347
ML
37#include <IOKit/IOKitLib.h>
38#include <IOKit/serial/IOSerialKeys.h>
39#include <sys/syslimits.h>
3b63f34d
ML
40#endif
41#ifdef __linux__
42#include "libudev.h"
4b97c9fc 43#include "linux/serial.h"
3b63f34d 44#endif
74510d4b
ML
45
46#include "serialport.h"
47
5919c913 48static struct sp_port *sp_port_new(const char *portname)
d54e9004
ML
49{
50 struct sp_port *port;
5919c913 51 int len;
d54e9004
ML
52
53 if (!(port = malloc(sizeof(struct sp_port))))
54 return NULL;
55
5919c913
ML
56 len = strlen(portname) + 1;
57
d54e9004
ML
58 if (!(port->name = malloc(len)))
59 {
60 free(port);
61 return NULL;
62 }
63
64 memcpy(port->name, portname, len);
65
66 return port;
67}
68
5919c913 69static struct sp_port **sp_list_append(struct sp_port **list, const char *portname)
3b63f34d
ML
70{
71 void *tmp;
72 unsigned int count;
73 for (count = 0; list[count]; count++);
d54e9004 74 if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
3b63f34d
ML
75 goto fail;
76 list = tmp;
5919c913 77 if (!(list[count] = sp_port_new(portname)))
3b63f34d 78 goto fail;
db2794ce 79 list[count + 1] = NULL;
3b63f34d
ML
80 return list;
81fail:
82 sp_free_port_list(list);
83 return NULL;
84}
85
68ab64cc
ML
86/**
87 * List the serial ports available on the system.
88 *
89 * @return A null-terminated array of port name strings.
90 */
d54e9004 91struct sp_port **sp_list_ports(void)
3b63f34d 92{
d54e9004 93 struct sp_port **list;
24c1a4bb 94
d54e9004 95 if (!(list = malloc(sizeof(struct sp_port **))))
24c1a4bb
ML
96 return NULL;
97
98 list[0] = NULL;
3b63f34d
ML
99
100#ifdef _WIN32
101 HKEY key;
bdfb5b8c
ML
102 TCHAR *value, *data;
103 DWORD max_value_len, max_data_size, max_data_len;
104 DWORD value_len, data_size, data_len;
3b63f34d 105 DWORD type, index = 0;
8b532d9c
ML
106 char *name;
107 int name_len;
3b63f34d
ML
108
109 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
110 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
111 return NULL;
112 if (RegQueryInfoKey(key, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
bdfb5b8c 113 &max_value_len, &max_data_size, NULL, NULL) != ERROR_SUCCESS)
3b63f34d
ML
114 goto out_close;
115 max_data_len = max_data_size / sizeof(TCHAR);
bdfb5b8c 116 if (!(value = malloc((max_value_len + 1) * sizeof(TCHAR))))
3b63f34d
ML
117 goto out_close;
118 if (!(data = malloc((max_data_len + 1) * sizeof(TCHAR))))
bdfb5b8c 119 goto out_free_value;
3b63f34d 120 while (
bdfb5b8c 121 value_len = max_value_len,
3b63f34d 122 data_size = max_data_size,
bdfb5b8c 123 RegEnumValue(key, index, value, &value_len,
3b63f34d
ML
124 NULL, &type, (LPBYTE)data, &data_size) == ERROR_SUCCESS)
125 {
126 data_len = data_size / sizeof(TCHAR);
127 data[data_len] = '\0';
8b532d9c
ML
128#ifdef UNICODE
129 name_len = WideCharToMultiByte(CP_ACP, 0, data, -1, NULL, 0, NULL, NULL)
130#else
131 name_len = data_len + 1;
132#endif
133 if (!(name = malloc(name_len)))
134 goto out;
135#ifdef UNICODE
136 WideCharToMultiByte(CP_ACP, 0, data, -1, name, name_len, NULL, NULL);
137#else
138 strcpy(name, data);
139#endif
3b63f34d 140 if (type == REG_SZ)
5919c913 141 if (!(list = sp_list_append(list, name)))
3b63f34d
ML
142 goto out;
143 index++;
144 }
145out:
146 free(data);
bdfb5b8c
ML
147out_free_value:
148 free(value);
3b63f34d
ML
149out_close:
150 RegCloseKey(key);
151 return list;
152#endif
153#ifdef __APPLE__
154 mach_port_t master;
155 CFMutableDictionaryRef classes;
156 io_iterator_t iter;
157 char *path;
158 io_object_t port;
159 CFTypeRef cf_path;
160 Boolean result;
161
162 if (IOMasterPort(MACH_PORT_NULL, &master) != KERN_SUCCESS)
163 return NULL;
164
165 if (!(classes = IOServiceMatching(kIOSerialBSDServiceValue)))
166 return NULL;
167
168 CFDictionarySetValue(classes,
169 CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
170
171 if (!(IOServiceGetMatchingServices(master, classes, &iter)))
172 return NULL;
173
174 if (!(path = malloc(PATH_MAX)))
175 goto out_release;
176
1ebf4347 177 while ((port = IOIteratorNext(iter))) {
3b63f34d
ML
178 cf_path = IORegistryEntryCreateCFProperty(port,
179 CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0);
180 if (cf_path) {
181 result = CFStringGetCString(cf_path,
182 path, PATH_MAX, kCFStringEncodingASCII);
183 CFRelease(cf_path);
184 if (result)
5919c913 185 if (!(list = sp_list_append(list, path)))
3b63f34d
ML
186 {
187 IOObjectRelease(port);
188 goto out;
189 }
190 }
191 IOObjectRelease(port);
192 }
193
194out:
195 free(path);
196out_release:
197 IOObjectRelease(iter);
198 return list;
199#endif
200#ifdef __linux__
201 struct udev *ud;
202 struct udev_enumerate *ud_enumerate;
203 struct udev_list_entry *ud_list;
204 struct udev_list_entry *ud_entry;
205 const char *path;
08fe0bdb 206 struct udev_device *ud_dev, *ud_parent;
3b63f34d 207 const char *name;
4b97c9fc
ML
208 const char *driver;
209 int fd, ioctl_result;
210 struct serial_struct serial_info;
3b63f34d
ML
211
212 ud = udev_new();
213 ud_enumerate = udev_enumerate_new(ud);
214 udev_enumerate_add_match_subsystem(ud_enumerate, "tty");
215 udev_enumerate_scan_devices(ud_enumerate);
216 ud_list = udev_enumerate_get_list_entry(ud_enumerate);
3b63f34d
ML
217 udev_list_entry_foreach(ud_entry, ud_list)
218 {
219 path = udev_list_entry_get_name(ud_entry);
220 ud_dev = udev_device_new_from_syspath(ud, path);
08fe0bdb
ML
221 /* If there is no parent device, this is a virtual tty. */
222 ud_parent = udev_device_get_parent(ud_dev);
223 if (ud_parent == NULL)
224 {
225 udev_device_unref(ud_dev);
226 continue;
227 }
3b63f34d 228 name = udev_device_get_devnode(ud_dev);
4b97c9fc
ML
229 /* The serial8250 driver has a hardcoded number of ports.
230 * The only way to tell which actually exist on a given system
231 * is to try to open them and make an ioctl call. */
232 driver = udev_device_get_driver(ud_parent);
233 if (driver && !strcmp(driver, "serial8250"))
234 {
235 if ((fd = open(name, O_RDWR | O_NONBLOCK | O_NOCTTY)) < 0)
236 goto skip;
237 ioctl_result = ioctl(fd, TIOCGSERIAL, &serial_info);
238 close(fd);
239 if (ioctl_result != 0)
240 goto skip;
241 if (serial_info.type == PORT_UNKNOWN)
242 goto skip;
243 }
5919c913 244 list = sp_list_append(list, name);
4b97c9fc 245skip:
3b63f34d
ML
246 udev_device_unref(ud_dev);
247 if (!list)
248 goto out;
249 }
250out:
251 udev_enumerate_unref(ud_enumerate);
252 udev_unref(ud);
253 return list;
254#endif
255}
256
68ab64cc
ML
257/**
258 * Free a port list returned by sp_list_ports.
259 */
d54e9004 260void sp_free_port_list(struct sp_port **list)
3b63f34d
ML
261{
262 unsigned int i;
263 for (i = 0; list[i]; i++)
264 free(list[i]);
265 free(list);
266}
267
74510d4b
ML
268static int sp_validate_port(struct sp_port *port)
269{
270 if (port == NULL)
271 return 0;
272#ifdef _WIN32
273 if (port->hdl == INVALID_HANDLE_VALUE)
274 return 0;
275#else
276 if (port->fd < 0)
277 return 0;
278#endif
279 return 1;
280}
281
282#define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
283
284/**
285 * Open the specified serial port.
286 *
287 * @param port Pointer to empty port structure allocated by caller.
288 * @param portname Name of port to open.
289 * @param flags Flags to use when opening the serial port. Possible flags
290 * are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
291 *
292 * @return SP_OK on success, SP_ERR_FAIL on failure,
293 * or SP_ERR_ARG if an invalid port or name is passed.
294 */
d54e9004 295int sp_open(struct sp_port *port, int flags)
74510d4b
ML
296{
297 if (!port)
298 return SP_ERR_ARG;
299
74510d4b
ML
300#ifdef _WIN32
301 DWORD desired_access = 0, flags_and_attributes = 0;
302 /* Map 'flags' to the OS-specific settings. */
303 desired_access |= GENERIC_READ;
304 flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
305 if (flags & SP_MODE_RDWR)
306 desired_access |= GENERIC_WRITE;
307 if (flags & SP_MODE_NONBLOCK)
308 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
309
310 port->hdl = CreateFile(port->name, desired_access, 0, 0,
311 OPEN_EXISTING, flags_and_attributes, 0);
312 if (port->hdl == INVALID_HANDLE_VALUE)
313 return SP_ERR_FAIL;
314#else
315 int flags_local = 0;
316 /* Map 'flags' to the OS-specific settings. */
317 if (flags & SP_MODE_RDWR)
318 flags_local |= O_RDWR;
319 if (flags & SP_MODE_RDONLY)
320 flags_local |= O_RDONLY;
321 if (flags & SP_MODE_NONBLOCK)
322 flags_local |= O_NONBLOCK;
323
324 if ((port->fd = open(port->name, flags_local)) < 0)
325 return SP_ERR_FAIL;
326#endif
327
328 return SP_OK;
329}
330
331/**
332 * Close the specified serial port.
333 *
334 * @param port Pointer to port structure.
335 *
336 * @return SP_OK on success, SP_ERR_FAIL on failure,
337 * or SP_ERR_ARG if an invalid port is passed.
338 */
339int sp_close(struct sp_port *port)
340{
341 CHECK_PORT();
342
343#ifdef _WIN32
344 /* Returns non-zero upon success, 0 upon failure. */
345 if (CloseHandle(port->hdl) == 0)
346 return SP_ERR_FAIL;
347#else
348 /* Returns 0 upon success, -1 upon failure. */
349 if (close(port->fd) == -1)
350 return SP_ERR_FAIL;
351#endif
352
353 return SP_OK;
354}
355
356/**
357 * Flush serial port buffers.
358 *
359 * @param port Pointer to port structure.
360 *
361 * @return SP_OK on success, SP_ERR_FAIL on failure,
362 * or SP_ERR_ARG if an invalid port is passed.
363 */
364int sp_flush(struct sp_port *port)
365{
366 CHECK_PORT();
367
368#ifdef _WIN32
369 /* Returns non-zero upon success, 0 upon failure. */
370 if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
371 return SP_ERR_FAIL;
372#else
373 /* Returns 0 upon success, -1 upon failure. */
374 if (tcflush(port->fd, TCIOFLUSH) < 0)
375 return SP_ERR_FAIL;
376#endif
377 return SP_OK;
378}
379
380/**
381 * Write a number of bytes to the specified serial port.
382 *
383 * @param port Pointer to port structure.
384 * @param buf Buffer containing the bytes to write.
385 * @param count Number of bytes to write.
386 *
387 * @return The number of bytes written, SP_ERR_FAIL on failure,
388 * or SP_ERR_ARG if an invalid port is passed.
389 */
390int sp_write(struct sp_port *port, const void *buf, size_t count)
391{
392 CHECK_PORT();
393
394 if (!buf)
395 return SP_ERR_ARG;
396
397#ifdef _WIN32
398 DWORD written = 0;
399 /* Returns non-zero upon success, 0 upon failure. */
400 if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
401 return SP_ERR_FAIL;
402 return written;
403#else
404 /* Returns the number of bytes written, or -1 upon failure. */
405 ssize_t written = write(port->fd, buf, count);
406 if (written < 0)
407 return SP_ERR_FAIL;
408 else
409 return written;;
410#endif
411}
412
413/**
414 * Read a number of bytes from the specified serial port.
415 *
416 * @param port Pointer to port structure.
417 * @param buf Buffer where to store the bytes that are read.
418 * @param count The number of bytes to read.
419 *
420 * @return The number of bytes read, SP_ERR_FAIL on failure,
421 * or SP_ERR_ARG if an invalid port is passed.
422 */
423int sp_read(struct sp_port *port, void *buf, size_t count)
424{
425 CHECK_PORT();
426
427 if (!buf)
428 return SP_ERR_ARG;
429
430#ifdef _WIN32
431 DWORD bytes_read = 0;
432 /* Returns non-zero upon success, 0 upon failure. */
433 if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
434 return SP_ERR_FAIL;
435 return bytes_read;
436#else
437 ssize_t bytes_read;
438 /* Returns the number of bytes read, or -1 upon failure. */
439 if ((bytes_read = read(port->fd, buf, count)) < 0)
440 return SP_ERR_FAIL;
441 return bytes_read;
442#endif
443}
444
445/**
446 * Set serial parameters for the specified serial port.
447 *
448 * @param port Pointer to port structure.
449 * @param baudrate The baudrate to set.
450 * @param bits The number of data bits to use.
451 * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
452 * @param stopbits The number of stop bits to use (1 or 2).
453 * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
454 * 2 = XON/XOFF).
455 *
456 * @return The number of bytes read, SP_ERR_FAIL on failure,
457 * or SP_ERR_ARG if an invalid argument is passed.
458 */
459int sp_set_params(struct sp_port *port, int baudrate,
460 int bits, int parity, int stopbits,
461 int flowcontrol, int rts, int dtr)
462{
463 CHECK_PORT();
464
465#ifdef _WIN32
466 DCB dcb;
467
468 if (!GetCommState(port->hdl, &dcb))
469 return SP_ERR_FAIL;
470
471 switch (baudrate) {
472 /*
473 * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
474 * have documented CBR_* macros.
475 */
476 case 110:
477 dcb.BaudRate = CBR_110;
478 break;
479 case 300:
480 dcb.BaudRate = CBR_300;
481 break;
482 case 600:
483 dcb.BaudRate = CBR_600;
484 break;
485 case 1200:
486 dcb.BaudRate = CBR_1200;
487 break;
488 case 2400:
489 dcb.BaudRate = CBR_2400;
490 break;
491 case 4800:
492 dcb.BaudRate = CBR_4800;
493 break;
494 case 9600:
495 dcb.BaudRate = CBR_9600;
496 break;
497 case 14400:
498 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
499 break;
500 case 19200:
501 dcb.BaudRate = CBR_19200;
502 break;
503 case 38400:
504 dcb.BaudRate = CBR_38400;
505 break;
506 case 57600:
507 dcb.BaudRate = CBR_57600;
508 break;
509 case 115200:
510 dcb.BaudRate = CBR_115200;
511 break;
512 case 128000:
513 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
514 break;
515 case 256000:
516 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
517 break;
518 default:
519 return SP_ERR_ARG;
520 }
521
522 switch (stopbits) {
523 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
524 case 1:
525 dcb.StopBits = ONESTOPBIT;
526 break;
527 case 2:
528 dcb.StopBits = TWOSTOPBITS;
529 break;
530 default:
531 return SP_ERR_ARG;
532 }
533
534 switch (parity) {
535 /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
536 case SP_PARITY_NONE:
537 dcb.Parity = NOPARITY;
538 break;
539 case SP_PARITY_EVEN:
540 dcb.Parity = EVENPARITY;
541 break;
542 case SP_PARITY_ODD:
543 dcb.Parity = ODDPARITY;
544 break;
545 default:
546 return SP_ERR_ARG;
547 }
548
549 if (rts != -1) {
550 if (rts)
551 dcb.fRtsControl = RTS_CONTROL_ENABLE;
552 else
553 dcb.fRtsControl = RTS_CONTROL_DISABLE;
554 }
555
556 if (dtr != -1) {
557 if (dtr)
558 dcb.fDtrControl = DTR_CONTROL_ENABLE;
559 else
560 dcb.fDtrControl = DTR_CONTROL_DISABLE;
561 }
562
563 if (!SetCommState(port->hdl, &dcb))
564 return SP_ERR_FAIL;
565#else
566 struct termios term;
567 speed_t baud;
568 int controlbits;
569
570 if (tcgetattr(port->fd, &term) < 0)
571 return SP_ERR_FAIL;
572
573 switch (baudrate) {
574 case 50:
575 baud = B50;
576 break;
577 case 75:
578 baud = B75;
579 break;
580 case 110:
581 baud = B110;
582 break;
583 case 134:
584 baud = B134;
585 break;
586 case 150:
587 baud = B150;
588 break;
589 case 200:
590 baud = B200;
591 break;
592 case 300:
593 baud = B300;
594 break;
595 case 600:
596 baud = B600;
597 break;
598 case 1200:
599 baud = B1200;
600 break;
601 case 1800:
602 baud = B1800;
603 break;
604 case 2400:
605 baud = B2400;
606 break;
607 case 4800:
608 baud = B4800;
609 break;
610 case 9600:
611 baud = B9600;
612 break;
613 case 19200:
614 baud = B19200;
615 break;
616 case 38400:
617 baud = B38400;
618 break;
619 case 57600:
620 baud = B57600;
621 break;
622 case 115200:
623 baud = B115200;
624 break;
625 case 230400:
626 baud = B230400;
627 break;
628#if !defined(__APPLE__) && !defined(__OpenBSD__)
629 case 460800:
630 baud = B460800;
631 break;
632#endif
633 default:
634 return SP_ERR_ARG;
635 }
636
637 if (cfsetospeed(&term, baud) < 0)
638 return SP_ERR_FAIL;
639
640 if (cfsetispeed(&term, baud) < 0)
641 return SP_ERR_FAIL;
642
643 term.c_cflag &= ~CSIZE;
644 switch (bits) {
645 case 8:
646 term.c_cflag |= CS8;
647 break;
648 case 7:
649 term.c_cflag |= CS7;
650 break;
651 default:
652 return SP_ERR_ARG;
653 }
654
655 term.c_cflag &= ~CSTOPB;
656 switch (stopbits) {
657 case 1:
658 term.c_cflag &= ~CSTOPB;
659 break;
660 case 2:
661 term.c_cflag |= CSTOPB;
662 break;
663 default:
664 return SP_ERR_ARG;
665 }
666
8683177b 667 term.c_iflag &= ~(IXON | IXOFF | IXANY);
74510d4b
ML
668 term.c_cflag &= ~CRTSCTS;
669 switch (flowcontrol) {
670 case 0:
671 /* No flow control. */
672 break;
673 case 1:
674 term.c_cflag |= CRTSCTS;
675 break;
676 case 2:
8683177b 677 term.c_iflag |= IXON | IXOFF | IXANY;
74510d4b
ML
678 break;
679 default:
680 return SP_ERR_ARG;
681 }
682
683 term.c_iflag &= ~IGNPAR;
8683177b 684 term.c_cflag &= ~(PARENB | PARODD);
74510d4b
ML
685 switch (parity) {
686 case SP_PARITY_NONE:
687 term.c_iflag |= IGNPAR;
688 break;
689 case SP_PARITY_EVEN:
690 term.c_cflag |= PARENB;
691 break;
692 case SP_PARITY_ODD:
693 term.c_cflag |= PARENB | PARODD;
694 break;
695 default:
696 return SP_ERR_ARG;
697 }
698
699 /* Turn off all serial port cooking. */
700 term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
701 term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
702#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
703 term.c_oflag &= ~OFILL;
704#endif
705
706 /* Disable canonical mode, and don't echo input characters. */
707 term.c_lflag &= ~(ICANON | ECHO);
708
8683177b
ML
709 /* Ignore modem status lines; enable receiver */
710 term.c_cflag |= (CLOCAL | CREAD);
711
74510d4b
ML
712 /* Write the configured settings. */
713 if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
714 return SP_ERR_FAIL;
715
716 if (rts != -1) {
717 controlbits = TIOCM_RTS;
718 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
719 &controlbits) < 0)
720 return SP_ERR_FAIL;
721 }
722
723 if (dtr != -1) {
724 controlbits = TIOCM_DTR;
725 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
726 &controlbits) < 0)
727 return SP_ERR_FAIL;
728 }
729#endif
730
731 return SP_OK;
732}
733
734/**
735 * Get error code for failed operation.
736 *
737 * In order to obtain the correct result, this function should be called
738 * straight after the failure, before executing any other system operations.
739 *
740 * @return The system's numeric code for the error that caused the last
741 * operation to fail.
742 */
743int sp_last_error_code(void)
744{
745#ifdef _WIN32
746 return GetLastError();
747#else
748 return errno;
749#endif
750}
751
752/**
753 * Get error message for failed operation.
754 *
755 * In order to obtain the correct result, this function should be called
756 * straight after the failure, before executing other system operations.
757 *
758 * @return The system's message for the error that caused the last
759 * operation to fail. This string may be allocated by the function,
760 * and can be freed after use by calling sp_free_error_message.
761 */
762char *sp_last_error_message(void)
763{
764#ifdef _WIN32
765 LPVOID message;
766 DWORD error = GetLastError();
767
768 FormatMessage(
769 FORMAT_MESSAGE_ALLOCATE_BUFFER |
770 FORMAT_MESSAGE_FROM_SYSTEM |
771 FORMAT_MESSAGE_IGNORE_INSERTS,
772 NULL,
773 error,
774 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
775 (LPTSTR) &message,
776 0, NULL );
777
778 return message;
779#else
780 return strerror(errno);
781#endif
782}
783
784/**
785 * Free error message.
786 *
787 * This function can be used to free a string returned by the
788 * sp_last_error_message function.
789 */
790void sp_free_error_message(char *message)
791{
792#ifdef _WIN32
793 LocalFree(message);
64eec30d
ML
794#else
795 (void)message;
74510d4b
ML
796#endif
797}