vi_utils.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. /*
  2. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  3. */
  4. #include "vi_utils.h"
  5. #define DBG_TAG "vi"
  6. #define DBG_LVL DBG_INFO
  7. #include <rtdbg.h>
  8. #include <rtconfig.h>
  9. #ifndef VI_SANDBOX_SIZE_KB
  10. #define VI_SANDBOX_SIZE_KB 20 /* KB */
  11. #endif
  12. static const char *vi_outof_momory_warning = "vi sandbox runs out of memory, please enlarge VI_SANDBOX_SIZE_KB";
  13. int index_in_strings(const char *strings, const char *key)
  14. {
  15. int j, idx = 0;
  16. while (*strings) {
  17. /* Do we see "key\0" at current position in strings? */
  18. for (j = 0; *strings == key[j]; ++j) {
  19. if (*strings++ == '\0') {
  20. //bb_error_msg("found:'%s' i:%u", key, idx);
  21. return idx; /* yes */
  22. }
  23. }
  24. /* No. Move to the start of the next string. */
  25. while (*strings++ != '\0')
  26. continue;
  27. idx++;
  28. }
  29. return -1;
  30. }
  31. #ifdef VI_ENABLE_COLON
  32. /* Find out if the last character of a string matches the one given */
  33. char* last_char_is(const char *s, int c)
  34. {
  35. if (!s[0])
  36. return NULL;
  37. while (s[1])
  38. s++;
  39. return (*s == (char)c) ? (char *) s : NULL;
  40. }
  41. #endif
  42. #if defined(_MSC_VER) || defined(__CC_ARM) || defined(__ICCARM__)
  43. void *memrchr(const void* ptr, int ch, size_t pos)
  44. {
  45. char *end = (char *)ptr+pos-1;
  46. while (end != ptr)
  47. {
  48. if (*end == ch)
  49. return end;
  50. end--;
  51. }
  52. return (*end == ch)?(end):(NULL);
  53. }
  54. #ifndef __ICCARM__
  55. int isblank(int ch)
  56. {
  57. if (ch == ' ' || ch == '\t')
  58. return 1;
  59. return 0;
  60. }
  61. #endif
  62. #endif
  63. #ifdef VI_ENABLE_SETOPTS
  64. char* skip_whitespace(const char *s)
  65. {
  66. /* In POSIX/C locale (the only locale we care about: do we REALLY want
  67. * to allow Unicode whitespace in, say, .conf files? nuts!)
  68. * isspace is only these chars: "\t\n\v\f\r" and space.
  69. * "\t\n\v\f\r" happen to have ASCII codes 9,10,11,12,13.
  70. * Use that.
  71. */
  72. while (*s == ' ' || (unsigned char)(*s - 9) <= (13 - 9))
  73. s++;
  74. return (char *) s;
  75. }
  76. char* skip_non_whitespace(const char *s)
  77. {
  78. while (*s != '\0' && *s != ' ' && (unsigned char)(*s - 9) > (13 - 9))
  79. s++;
  80. return (char *) s;
  81. }
  82. #endif
  83. ssize_t safe_read(int fd, void *buf, size_t count)
  84. {
  85. ssize_t n;
  86. for (;;) {
  87. n = read(fd, buf, count);
  88. if (n >= 0 || errno != EINTR)
  89. break;
  90. /* Some callers set errno=0, are upset when they see EINTR.
  91. * Returning EINTR is wrong since we retry read(),
  92. * the "error" was transient.
  93. */
  94. errno = 0;
  95. /* repeat the read() */
  96. }
  97. return n;
  98. }
  99. /*
  100. * Read all of the supplied buffer from a file.
  101. * This does multiple reads as necessary.
  102. * Returns the amount read, or -1 on an error.
  103. * A short read is returned on an end of file.
  104. */
  105. ssize_t full_read(int fd, void *buf, size_t len)
  106. {
  107. ssize_t cc;
  108. ssize_t total;
  109. total = 0;
  110. while (len) {
  111. cc = safe_read(fd, buf, len);
  112. if (cc < 0) {
  113. if (total) {
  114. /* we already have some! */
  115. /* user can do another read to know the error code */
  116. return total;
  117. }
  118. return cc; /* read() returns -1 on failure. */
  119. }
  120. if (cc == 0)
  121. break;
  122. buf = ((char *)buf) + cc;
  123. total += cc;
  124. len -= cc;
  125. }
  126. return total;
  127. }
  128. ssize_t safe_write(int fd, const void *buf, size_t count)
  129. {
  130. ssize_t n;
  131. for (;;) {
  132. n = write(fd, buf, count);
  133. if (n >= 0 || errno != EINTR)
  134. break;
  135. /* Some callers set errno=0, are upset when they see EINTR.
  136. * Returning EINTR is wrong since we retry write(),
  137. * the "error" was transient.
  138. */
  139. errno = 0;
  140. /* repeat the write() */
  141. }
  142. return n;
  143. }
  144. /*
  145. * Write all of the supplied buffer out to a file.
  146. * This does multiple writes as necessary.
  147. * Returns the amount written, or -1 if error was seen
  148. * on the very first write.
  149. */
  150. ssize_t full_write(int fd, const void *buf, size_t len)
  151. {
  152. ssize_t cc;
  153. ssize_t total;
  154. total = 0;
  155. while (len) {
  156. cc = safe_write(fd, buf, len);
  157. if (cc < 0) {
  158. if (total) {
  159. /* we already wrote some! */
  160. /* user can do another write to know the error code */
  161. return total;
  162. }
  163. return cc; /* write() returns -1 on failure. */
  164. }
  165. total += cc;
  166. buf = ((const char *)buf) + cc;
  167. len -= cc;
  168. }
  169. return total;
  170. }
  171. /* Wrapper which restarts poll on EINTR or ENOMEM.
  172. * On other errors does perror("poll") and returns.
  173. * Warning! May take longer than timeout_ms to return! */
  174. int safe_poll(struct pollfd *ufds, nfds_t nfds, int timeout)
  175. {
  176. while (1) {
  177. int n = poll(ufds, nfds, timeout);
  178. if (n >= 0)
  179. return n;
  180. /* Make sure we inch towards completion */
  181. if (timeout > 0)
  182. timeout--;
  183. /* E.g. strace causes poll to return this */
  184. if (errno == EINTR)
  185. continue;
  186. /* Kernel is very low on memory. Retry. */
  187. /* I doubt many callers would handle this correctly! */
  188. if (errno == ENOMEM)
  189. continue;
  190. printf("poll");
  191. return n;
  192. }
  193. }
  194. static mem_sandbox_t vi_sandbox = RT_NULL;
  195. unsigned char vi_mem_init(void)
  196. {
  197. vi_sandbox = mem_sandbox_create(VI_SANDBOX_SIZE_KB * 1024);
  198. if(vi_sandbox == RT_NULL)
  199. {
  200. LOG_E("vi sandbox create error");
  201. return 0;
  202. }
  203. else
  204. {
  205. return 1;
  206. }
  207. }
  208. void vi_mem_release(void)
  209. {
  210. mem_sandbox_delete(vi_sandbox);
  211. }
  212. void *vi_malloc(rt_size_t size)
  213. {
  214. void * p;
  215. p = mem_sandbox_malloc(vi_sandbox, size);
  216. if(p == RT_NULL)
  217. {
  218. LOG_E(vi_outof_momory_warning);
  219. RT_ASSERT(p != RT_NULL);
  220. return RT_NULL;
  221. }
  222. return p;
  223. }
  224. void *vi_realloc(void *rmem, rt_size_t newsize)
  225. {
  226. void *p;
  227. p = mem_sandbox_realloc(vi_sandbox, rmem, newsize);
  228. if(p == RT_NULL && newsize != 0)
  229. {
  230. LOG_E(vi_outof_momory_warning);
  231. RT_ASSERT(p != RT_NULL);
  232. return RT_NULL;
  233. }
  234. return p;
  235. }
  236. void vi_free(void *ptr)
  237. {
  238. mem_sandbox_free(vi_sandbox, ptr);
  239. }
  240. void* vi_zalloc(size_t size)
  241. {
  242. void *ptr = vi_malloc(size);
  243. rt_memset(ptr, 0, size);
  244. return ptr;
  245. }
  246. char *vi_strdup(const char *s)
  247. {
  248. void *p;
  249. p = mem_sandbox_strdup(vi_sandbox, s);
  250. if(p == RT_NULL)
  251. {
  252. LOG_E(vi_outof_momory_warning);
  253. RT_ASSERT(p != RT_NULL);
  254. return RT_NULL;
  255. }
  256. return p;
  257. }
  258. char *vi_strndup(const char *s, size_t n)
  259. {
  260. void *p;
  261. p = mem_sandbox_strndup(vi_sandbox, s, n);
  262. if(p == RT_NULL)
  263. {
  264. LOG_E(vi_outof_momory_warning);
  265. RT_ASSERT(p != RT_NULL);
  266. return RT_NULL;
  267. }
  268. return p;
  269. }
  270. int64_t read_key(int fd, char *buffer, int timeout)
  271. {
  272. struct pollfd pfd;
  273. const char *seq;
  274. int n;
  275. /* Known escape sequences for cursor and function keys.
  276. * See "Xterm Control Sequences"
  277. * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
  278. */
  279. static const char esccmds[] ALIGN1 = {
  280. 'O','A' |0x80, (char) KEYCODE_UP ,
  281. 'O','B' |0x80, (char) KEYCODE_DOWN ,
  282. 'O','C' |0x80, (char) KEYCODE_RIGHT ,
  283. 'O','D' |0x80, (char) KEYCODE_LEFT ,
  284. 'O','H' |0x80, (char) KEYCODE_HOME ,
  285. 'O','F' |0x80, (char) KEYCODE_END ,
  286. #if 0
  287. 'O','P' |0x80, (char) KEYCODE_FUN1 ,
  288. /* [ESC] ESC O [2] P - [Alt-][Shift-]F1 */
  289. /* ESC [ O 1 ; 2 P - Shift-F1 */
  290. /* ESC [ O 1 ; 3 P - Alt-F1 */
  291. /* ESC [ O 1 ; 4 P - Alt-Shift-F1 */
  292. /* ESC [ O 1 ; 5 P - Ctrl-F1 */
  293. /* ESC [ O 1 ; 6 P - Ctrl-Shift-F1 */
  294. 'O','Q' |0x80, (char) KEYCODE_FUN2 ,
  295. 'O','R' |0x80, (char) KEYCODE_FUN3 ,
  296. 'O','S' |0x80, (char) KEYCODE_FUN4 ,
  297. #endif
  298. '[','A' |0x80, (char) KEYCODE_UP ,
  299. '[','B' |0x80, (char) KEYCODE_DOWN ,
  300. '[','C' |0x80, (char) KEYCODE_RIGHT ,
  301. '[','D' |0x80, (char) KEYCODE_LEFT ,
  302. /* ESC [ 1 ; 2 x, where x = A/B/C/D: Shift-<arrow> */
  303. /* ESC [ 1 ; 3 x, where x = A/B/C/D: Alt-<arrow> - implemented below */
  304. /* ESC [ 1 ; 4 x, where x = A/B/C/D: Alt-Shift-<arrow> */
  305. /* ESC [ 1 ; 5 x, where x = A/B/C/D: Ctrl-<arrow> - implemented below */
  306. /* ESC [ 1 ; 6 x, where x = A/B/C/D: Ctrl-Shift-<arrow> */
  307. /* ESC [ 1 ; 7 x, where x = A/B/C/D: Ctrl-Alt-<arrow> */
  308. /* ESC [ 1 ; 8 x, where x = A/B/C/D: Ctrl-Alt-Shift-<arrow> */
  309. '[','H' |0x80, (char) KEYCODE_HOME , /* xterm */
  310. '[','F' |0x80, (char) KEYCODE_END , /* xterm */
  311. /* [ESC] ESC [ [2] H - [Alt-][Shift-]Home (End similarly?) */
  312. /* '[','Z' |0x80, (char) KEYCODE_SHIFT_TAB, */
  313. '[','1','~' |0x80, (char) KEYCODE_HOME , /* vt100? linux vt? or what? */
  314. '[','2','~' |0x80, (char) KEYCODE_INSERT ,
  315. /* ESC [ 2 ; 3 ~ - Alt-Insert */
  316. '[','3','~' |0x80, (char) KEYCODE_DELETE ,
  317. /* [ESC] ESC [ 3 [;2] ~ - [Alt-][Shift-]Delete */
  318. /* ESC [ 3 ; 3 ~ - Alt-Delete */
  319. /* ESC [ 3 ; 5 ~ - Ctrl-Delete */
  320. '[','4','~' |0x80, (char) KEYCODE_END , /* vt100? linux vt? or what? */
  321. '[','5','~' |0x80, (char) KEYCODE_PAGEUP ,
  322. /* ESC [ 5 ; 3 ~ - Alt-PgUp */
  323. /* ESC [ 5 ; 5 ~ - Ctrl-PgUp */
  324. /* ESC [ 5 ; 7 ~ - Ctrl-Alt-PgUp */
  325. '[','6','~' |0x80, (char) KEYCODE_PAGEDOWN,
  326. '[','7','~' |0x80, (char) KEYCODE_HOME , /* vt100? linux vt? or what? */
  327. '[','8','~' |0x80, (char) KEYCODE_END , /* vt100? linux vt? or what? */
  328. #if 0
  329. '[','1','1','~'|0x80, (char) KEYCODE_FUN1 , /* old xterm, deprecated by ESC O P */
  330. '[','1','2','~'|0x80, (char) KEYCODE_FUN2 , /* old xterm... */
  331. '[','1','3','~'|0x80, (char) KEYCODE_FUN3 , /* old xterm... */
  332. '[','1','4','~'|0x80, (char) KEYCODE_FUN4 , /* old xterm... */
  333. '[','1','5','~'|0x80, (char) KEYCODE_FUN5 ,
  334. /* [ESC] ESC [ 1 5 [;2] ~ - [Alt-][Shift-]F5 */
  335. '[','1','7','~'|0x80, (char) KEYCODE_FUN6 ,
  336. '[','1','8','~'|0x80, (char) KEYCODE_FUN7 ,
  337. '[','1','9','~'|0x80, (char) KEYCODE_FUN8 ,
  338. '[','2','0','~'|0x80, (char) KEYCODE_FUN9 ,
  339. '[','2','1','~'|0x80, (char) KEYCODE_FUN10 ,
  340. '[','2','3','~'|0x80, (char) KEYCODE_FUN11 ,
  341. '[','2','4','~'|0x80, (char) KEYCODE_FUN12 ,
  342. /* ESC [ 2 4 ; 2 ~ - Shift-F12 */
  343. /* ESC [ 2 4 ; 3 ~ - Alt-F12 */
  344. /* ESC [ 2 4 ; 4 ~ - Alt-Shift-F12 */
  345. /* ESC [ 2 4 ; 5 ~ - Ctrl-F12 */
  346. /* ESC [ 2 4 ; 6 ~ - Ctrl-Shift-F12 */
  347. #endif
  348. /* '[','1',';','5','A' |0x80, (char) KEYCODE_CTRL_UP , - unused */
  349. /* '[','1',';','5','B' |0x80, (char) KEYCODE_CTRL_DOWN , - unused */
  350. '[','1',';','5','C' |0x80, (char) KEYCODE_CTRL_RIGHT,
  351. '[','1',';','5','D' |0x80, (char) KEYCODE_CTRL_LEFT ,
  352. /* '[','1',';','3','A' |0x80, (char) KEYCODE_ALT_UP , - unused */
  353. /* '[','1',';','3','B' |0x80, (char) KEYCODE_ALT_DOWN , - unused */
  354. '[','1',';','3','C' |0x80, (char) KEYCODE_ALT_RIGHT,
  355. '[','1',';','3','D' |0x80, (char) KEYCODE_ALT_LEFT ,
  356. /* '[','3',';','3','~' |0x80, (char) KEYCODE_ALT_DELETE, - unused */
  357. 0
  358. };
  359. pfd.fd = fd;
  360. pfd.events = POLLIN;
  361. buffer++; /* saved chars counter is in buffer[-1] now */
  362. start_over:
  363. errno = 0;
  364. n = (unsigned char)buffer[-1];
  365. if (n == 0) {
  366. /* If no data, wait for input.
  367. * If requested, wait TIMEOUT ms. TIMEOUT = -1 is useful
  368. * if fd can be in non-blocking mode.
  369. */
  370. if (timeout >= -1) {
  371. if (safe_poll(&pfd, 1, timeout) == 0) {
  372. /* Timed out */
  373. errno = EAGAIN;
  374. return -1;
  375. }
  376. }
  377. /* It is tempting to read more than one byte here,
  378. * but it breaks pasting. Example: at shell prompt,
  379. * user presses "c","a","t" and then pastes "\nline\n".
  380. * When we were reading 3 bytes here, we were eating
  381. * "li" too, and cat was getting wrong input.
  382. */
  383. n = safe_read(fd, buffer, 1);
  384. if (n <= 0)
  385. return -1;
  386. }
  387. {
  388. unsigned char c = buffer[0];
  389. n--;
  390. if (n)
  391. memmove(buffer, buffer + 1, n);
  392. /* Only ESC starts ESC sequences */
  393. if (c != 27) {
  394. buffer[-1] = n;
  395. return c;
  396. }
  397. }
  398. /* Loop through known ESC sequences */
  399. seq = esccmds;
  400. while (*seq != '\0') {
  401. /* n - position in sequence we did not read yet */
  402. int i = 0; /* position in sequence to compare */
  403. /* Loop through chars in this sequence */
  404. while (1) {
  405. /* So far escape sequence matched up to [i-1] */
  406. if (n <= i) {
  407. int read_num;
  408. /* Need more chars, read another one if it wouldn't block.
  409. * Note that escape sequences come in as a unit,
  410. * so if we block for long it's not really an escape sequence.
  411. * Timeout is needed to reconnect escape sequences
  412. * split up by transmission over a serial console. */
  413. if (safe_poll(&pfd, 1, 50) == 0) {
  414. /* No more data!
  415. * Array is sorted from shortest to longest,
  416. * we can't match anything later in array -
  417. * anything later is longer than this seq.
  418. * Break out of both loops. */
  419. goto got_all;
  420. }
  421. errno = 0;
  422. read_num = safe_read(fd, buffer + n, 1);
  423. if (read_num <= 0) {
  424. /* If EAGAIN, then fd is O_NONBLOCK and poll lied:
  425. * in fact, there is no data. */
  426. if (errno != EAGAIN) {
  427. /* otherwise: it's EOF/error */
  428. buffer[-1] = 0;
  429. return -1;
  430. }
  431. goto got_all;
  432. }
  433. n++;
  434. }
  435. if (buffer[i] != (seq[i] & 0x7f)) {
  436. /* This seq doesn't match, go to next */
  437. seq += i;
  438. /* Forward to last char */
  439. while (!(*seq & 0x80))
  440. seq++;
  441. /* Skip it and the keycode which follows */
  442. seq += 2;
  443. break;
  444. }
  445. if (seq[i] & 0x80) {
  446. /* Entire seq matched */
  447. n = 0;
  448. /* n -= i; memmove(...);
  449. * would be more correct,
  450. * but we never read ahead that much,
  451. * and n == i here. */
  452. buffer[-1] = 0;
  453. return (signed char)seq[i+1];
  454. }
  455. i++;
  456. }
  457. }
  458. /* We did not find matching sequence.
  459. * We possibly read and stored more input in buffer[] by now.
  460. * n = bytes read. Try to read more until we time out.
  461. */
  462. while (n < KEYCODE_BUFFER_SIZE-1) { /* 1 for count byte at buffer[-1] */
  463. int read_num;
  464. if (safe_poll(&pfd, 1, 50) == 0) {
  465. /* No more data! */
  466. break;
  467. }
  468. errno = 0;
  469. read_num = safe_read(fd, buffer + n, 1);
  470. if (read_num <= 0) {
  471. /* If EAGAIN, then fd is O_NONBLOCK and poll lied:
  472. * in fact, there is no data. */
  473. if (errno != EAGAIN) {
  474. /* otherwise: it's EOF/error */
  475. buffer[-1] = 0;
  476. return -1;
  477. }
  478. break;
  479. }
  480. n++;
  481. /* Try to decipher "ESC [ NNN ; NNN R" sequence */
  482. if ((ENABLE_FEATURE_VI_ASK_TERMINAL)
  483. && n >= 5
  484. && buffer[0] == '['
  485. && buffer[n-1] == 'R'
  486. && isdigit((unsigned char)buffer[1])
  487. ) {
  488. char *end;
  489. unsigned long row, col;
  490. row = strtoul(buffer + 1, &end, 10);
  491. if (*end != ';' || !isdigit((unsigned char)end[1]))
  492. continue;
  493. col = strtoul(end + 1, &end, 10);
  494. if (*end != 'R')
  495. continue;
  496. if (row < 1 || col < 1 || (row | col) > 0x7fff)
  497. continue;
  498. buffer[-1] = 0;
  499. /* Pack into "1 <row15bits> <col16bits>" 32-bit sequence */
  500. row |= ((unsigned)(-1) << 15);
  501. col |= (row << 16);
  502. /* Return it in high-order word */
  503. return ((int64_t) col << 32) | (uint32_t)KEYCODE_CURSOR_POS;
  504. }
  505. }
  506. got_all:
  507. if (n <= 1) {
  508. /* Alt-x is usually returned as ESC x.
  509. * Report ESC, x is remembered for the next call.
  510. */
  511. buffer[-1] = n;
  512. return 27;
  513. }
  514. /* We were doing "buffer[-1] = n; return c;" here, but this results
  515. * in unknown key sequences being interpreted as ESC + garbage.
  516. * This was not useful. Pretend there was no key pressed,
  517. * go and wait for a new keypress:
  518. */
  519. buffer[-1] = 0;
  520. goto start_over;
  521. }
  522. static int vasprintf(char **string_ptr, const char *format, va_list p)
  523. {
  524. int r;
  525. va_list p2;
  526. char buf[128];
  527. va_copy(p2, p);
  528. r = vsnprintf(buf, 128, format, p);
  529. va_end(p);
  530. /* Note: can't use xstrdup/xmalloc, they call vasprintf (us) on failure! */
  531. if (r < 128) {
  532. va_end(p2);
  533. *string_ptr = vi_strdup(buf);
  534. return (*string_ptr ? r : -1);
  535. }
  536. *string_ptr = vi_malloc(r+1);
  537. r = (*string_ptr ? vsnprintf(*string_ptr, r+1, format, p2) : -1);
  538. va_end(p2);
  539. return r;
  540. }
  541. // Die with an error message if we can't malloc() enough space and do an
  542. // sprintf() into that space.
  543. char* xasprintf(const char *format, ...)
  544. {
  545. va_list p;
  546. int r;
  547. char *string_ptr;
  548. va_start(p, format);
  549. r = vasprintf(&string_ptr, format, p);
  550. va_end(p);
  551. if (r < 0)
  552. printf("die_memory_exhausted"); //bb_die_memory_exhausted();
  553. return string_ptr;
  554. }
  555. #ifdef RT_USING_POSIX_TERMIOS
  556. static int wh_helper(int value, int def_val, const char *env_name, int *err)
  557. {
  558. /* Envvars override even if "value" from ioctl is valid (>0).
  559. * Rationale: it's impossible to guess what user wants.
  560. * For example: "man CMD | ...": should "man" format output
  561. * to stdout's width? stdin's width? /dev/tty's width? 80 chars?
  562. * We _cant_ know it. If "..." saves text for e.g. email,
  563. * then it's probably 80 chars.
  564. * If "..." is, say, "grep -v DISCARD | $PAGER", then user
  565. * would prefer his tty's width to be used!
  566. *
  567. * Since we don't know, at least allow user to do this:
  568. * "COLUMNS=80 man CMD | ..."
  569. */
  570. char *s = getenv(env_name);
  571. if (s) {
  572. value = atoi(s);
  573. /* If LINES/COLUMNS are set, pretend that there is
  574. * no error getting w/h, this prevents some ugly
  575. * cursor tricks by our callers */
  576. *err = 0;
  577. }
  578. if (value <= 1 || value >= 30000)
  579. value = def_val;
  580. return value;
  581. }
  582. int get_terminal_width_height(int fd, unsigned *width, unsigned *height)
  583. {
  584. struct winsize win;
  585. int err;
  586. int close_me = -1;
  587. if (fd == -1) {
  588. if (isatty(STDOUT_FILENO))
  589. fd = STDOUT_FILENO;
  590. else
  591. if (isatty(STDERR_FILENO))
  592. fd = STDERR_FILENO;
  593. else
  594. if (isatty(STDIN_FILENO))
  595. fd = STDIN_FILENO;
  596. else
  597. close_me = fd = open("/dev/tty", O_RDONLY);
  598. }
  599. win.ws_row = 0;
  600. win.ws_col = 0;
  601. /* I've seen ioctl returning 0, but row/col is (still?) 0.
  602. * We treat that as an error too. */
  603. err = ioctl(fd, TIOCGWINSZ, &win) != 0 || win.ws_row == 0;
  604. if (height)
  605. *height = wh_helper(win.ws_row, 24, "LINES", &err);
  606. if (width)
  607. *width = wh_helper(win.ws_col, 80, "COLUMNS", &err);
  608. if (close_me >= 0)
  609. close(close_me);
  610. return err;
  611. }
  612. int tcsetattr_stdin_TCSANOW(const struct termios *tp)
  613. {
  614. return tcsetattr(STDIN_FILENO, TCSANOW, tp);
  615. }
  616. static int get_termios_and_make_raw(int fd, struct termios *newterm, struct termios *oldterm, int flags)
  617. {
  618. //TODO: slattach, shell read might be adapted to use this too: grep for "tcsetattr", "[VTIME] = 0"
  619. int r;
  620. memset(oldterm, 0, sizeof(*oldterm)); /* paranoia */
  621. r = tcgetattr(fd, oldterm);
  622. *newterm = *oldterm;
  623. /* Turn off buffered input (ICANON)
  624. * Turn off echoing (ECHO)
  625. * and separate echoing of newline (ECHONL, normally off anyway)
  626. */
  627. newterm->c_lflag &= ~(ICANON | ECHO | ECHONL);
  628. if (flags & TERMIOS_CLEAR_ISIG) {
  629. /* dont recognize INT/QUIT/SUSP chars */
  630. newterm->c_lflag &= ~ISIG;
  631. }
  632. /* reads will block only if < 1 char is available */
  633. newterm->c_cc[VMIN] = 1;
  634. /* no timeout (reads block forever) */
  635. newterm->c_cc[VTIME] = 0;
  636. /* IXON, IXOFF, and IXANY:
  637. * IXOFF=1: sw flow control is enabled on input queue:
  638. * tty transmits a STOP char when input queue is close to full
  639. * and transmits a START char when input queue is nearly empty.
  640. * IXON=1: sw flow control is enabled on output queue:
  641. * tty will stop sending if STOP char is received,
  642. * and resume sending if START is received, or if any char
  643. * is received and IXANY=1.
  644. */
  645. if (flags & TERMIOS_RAW_CRNL_INPUT) {
  646. /* IXON=0: XON/XOFF chars are treated as normal chars (why we do this?) */
  647. /* dont convert CR to NL on input */
  648. newterm->c_iflag &= ~(IXON | ICRNL);
  649. }
  650. if (flags & TERMIOS_RAW_CRNL_OUTPUT) {
  651. /* dont convert NL to CR+NL on output */
  652. newterm->c_oflag &= ~(ONLCR);
  653. /* Maybe clear more c_oflag bits? Usually, only OPOST and ONLCR are set.
  654. * OPOST Enable output processing (reqd for OLCUC and *NL* bits to work)
  655. * OLCUC Map lowercase characters to uppercase on output.
  656. * OCRNL Map CR to NL on output.
  657. * ONOCR Don't output CR at column 0.
  658. * ONLRET Don't output CR.
  659. */
  660. }
  661. if (flags & TERMIOS_RAW_INPUT) {
  662. #ifndef IMAXBEL
  663. # define IMAXBEL 0
  664. #endif
  665. #ifndef IUCLC
  666. # define IUCLC 0
  667. #endif
  668. #ifndef IXANY
  669. # define IXANY 0
  670. #endif
  671. /* IXOFF=0: disable sending XON/XOFF if input buf is full
  672. * IXON=0: input XON/XOFF chars are not special
  673. * BRKINT=0: dont send SIGINT on break
  674. * IMAXBEL=0: dont echo BEL on input line too long
  675. * INLCR,ICRNL,IUCLC: dont convert anything on input
  676. */
  677. newterm->c_iflag &= ~(IXOFF|IXON|IXANY|BRKINT|INLCR|ICRNL|IUCLC|IMAXBEL);
  678. }
  679. return r;
  680. }
  681. int set_termios_to_raw(int fd, struct termios *oldterm, int flags)
  682. {
  683. struct termios newterm;
  684. get_termios_and_make_raw(fd, &newterm, oldterm, flags);
  685. return tcsetattr(fd, TCSANOW, &newterm);
  686. }
  687. #endif /* RT_USING_POSIX_TERMIOS */
  688. #if defined(VI_ENABLE_SEARCH) && !defined(__GNUC__)
  689. char* strchrnul(const char *s, int c)
  690. {
  691. while (*s != '\0' && *s != c)
  692. s++;
  693. return (char*)s;
  694. }
  695. #endif