| /* A part of the Native C Library for Windows NT |
| Copyright 2007-2015 PC GO Ld. |
| |
| This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. |
| */ |
| |
| #include <windows.h> |
| #include <nt.h> |
| #include <errno.h> |
| #include <unistd.h> |
| #include <string.h> |
| |
| static int write_tty(const void *buffer, size_t count) { |
| //printf("nativelibc debug: function: write_tty(%p, %u)\n", buffer, count); |
| if(!count) return 0; |
| size_t len = strnlen(buffer, count) + 1; |
| if(len < count) { |
| const char *p = buffer; |
| //if(!len) return write_tty(p + 1, count - 1) + 1; |
| int r = write_tty(p, len); |
| if(r == -1) return -1; |
| r += write_tty(p + len, count - len); |
| return r; |
| } |
| len = count + 1; |
| wchar_t wbuffer[len]; |
| mbstowcs(wbuffer, buffer, len); |
| UNICODE_STRING wstrsut = { count * sizeof(wchar_t), len * sizeof(wchar_t), wbuffer }; |
| long int status = NtDisplayString(&wstrsut); |
| return __set_errno_from_ntstatus(status) ? -1 : count; |
| } |
| |
| int write(int fd, const void *buffer, size_t count) { |
| if(!buffer) { |
| errno = EFAULT; |
| return -1; |
| } |
| if(!count) return 0; |
| if(fd == STDIN_FILENO) { |
| errno = EBADF; |
| return -1; |
| } |
| if(fd == STDOUT_FILENO) { |
| int real_fd = _get_stdout_fd(); |
| switch(real_fd) { |
| case TTY_FD_INVALID: |
| errno = EBADF; |
| return -1; |
| case TTY_FD_DEFAULT: |
| return write_tty(buffer, count); |
| default: |
| fd = real_fd; |
| } |
| } else if(fd == STDERR_FILENO) { |
| int real_fd = _get_stderr_fd(); |
| switch(real_fd) { |
| case TTY_FD_INVALID: |
| errno = EBADF; |
| return -1; |
| case TTY_FD_DEFAULT: |
| return write_tty(buffer, count); |
| default: |
| fd = real_fd; |
| } |
| } |
| |
| IO_STATUS_BLOCK io_status; |
| long int status = NtWriteFile((void *)fd, NULL, NULL, NULL, &io_status, buffer, count, NULL, NULL); |
| //printf("nativelibc debug: write: status = 0x%lx\n", status); |
| if(__set_errno_from_ntstatus(status)) return -1; |
| return io_status.Information; |
| } |